#指定したStringで、instanceをdynamicに生成する
#インスタンス変数を動的に作成する
ruby 2.0.0p451 (2014-02-24 revision 45167) [x86_64-darwin13.1.0]
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
class Cat
def initialize(name)
@name = name
end
attr_accessor :name
#attr_reader :name
def say
puts "hello i'm #{@name}."
end
end
if __FILE__ == $0
class_name = "Cat"
name_of_cat = "chibi"
res = eval "@#{name_of_cat} = #{class_name}.new('#{name_of_cat}')"
p res
@chibi.say
puts "----"
puts
cat_name_list =["tama", "mike", "kuro"]
cat_name_list.each do | cat_name|
eval "@#{cat_name} = #{class_name}.new('#{cat_name}')"
end
cat_name_list.each do | cat_name |
eval "@#{cat_name}.say"
end
end
__END__
0 件のコメント:
コメントを投稿