情報学部 | 菅沼ホーム | 目次 | 索引 |
str = "def add(a, b)\nreturn a + b\nend" instance_eval(str) p add(10, 20)
class Test def initialize @par1 = 10 @par2 = 100 end end obj = Test.new p obj.instance_variable_get("@par1") p obj.instance_variable_get(:@par1) p obj.instance_variable_set("@par1", 20) p obj.instance_variables
10 10 20 ["@par2", "@par1"]
class Test def add(a, b) return a + b end def sub(a, b) return a - b end end obj = Test.new a = [obj.method("add"), obj.method(:sub)] p a[0].call(10, 20) # 30 を出力 p a[1].call(10, 20) # -10 を出力
class Test def add(a, b) return a + b end end obj = Test.new p obj.__send__("add", 10, 20) p obj.__send__(:add, 10, 20)
class Test def initialize(a = 0, b = 0) @real = a @imag = b end end obj1 = Test.new print obj1.instance_variable_get("@real"), " ", obj1.instance_variable_get("@imag"), "\n" obj2 = Test.new(10, 20) print obj2.instance_variable_get("@real"), " ", obj2.instance_variable_get("@imag")
情報学部 | 菅沼ホーム | 目次 | 索引 |