【Ruby】instance_variable_setで動的にインスタンス変数を定義する
instance_variable_setとは
オブジェクトのインスタンス変数に値をセットする組み込みメソッド
instance_valiable_setの注意点
指定するインスタンス変数名は@ を含める必要がある
シンボル、文字列でも指定可能
code: (ruby)
@name
:@name
'@name'
code: (ruby)
obj = Object.new
p obj.instance_variable_set(@foo, 1) #=> 1 p obj.instance_variable_set("@foo", 1) #=> 1 p obj.instance_variable_set(:@foo, 1) #=> 1 実装例
例) Fooの初期化時に3つのインスタンス変数にBarインスタンスを代入する
args は3つの値が入った配列
作成するインスタンス変数は@first、@second、@third の3つ
code: (ruby)
class Foo
attr_reader :first, :second, :third
def initialize(args)
# インスタンス変数名を配列で用意
instance_variables = %w(@first @second @third)
args.each_with_index do |arg, index|
# 動的に3つのインスタンス変数の作成と代入
instance_variable_set(instance_variablesindex, Bar.new(arg)) end
end
end
class Bar
def initialize(arg)
@arg = arg
end
end
=>
@first=#<Bar:0x00007f027ad0b6b8 @arg=1>,
@second=#<Bar:0x00007f027ad0b668 @arg=2>,
@third=#<Bar:0x00007f027ad0b640 @arg=3>>
foo.first
foo.second
foo.third