9 月 17 2008
[ruby] インスタンス変数を連番で作る
タイトルの通り。
Hogeクラスにhoge1〜hoge10までのインスタンス変数を作って、パブリックメソッドにする場合、以下のような感じで書ける。
class Hoge
attr_accessor *Array.new(10){|i| "hoge#{i}".to_sym }
def initialize
10.times do |i|
self.instance_variable_set("@hoge#{i}".to_sym,i)
end
end
end
hoge = Hoge.new
p hoge
p hoge.hoge1
attr_accessor *Array.new(10){|i| "hoge#{i}".to_sym }
def initialize
10.times do |i|
self.instance_variable_set("@hoge#{i}".to_sym,i)
end
end
end
hoge = Hoge.new
p hoge
p hoge.hoge1
もっときれいに書けるかな