2015年1月6日 星期二

[Ruby] class_eval and instance_eval 使用

class_eval 用來定義 Class 的 instance method.
instance_eval 用來定義該對象的 singleton_method.

class Person end Person.class_eval do def say_hello "Hello!" end end jimmy = Person.new jimmy.say_hello # "Hello!" class Person end Person.instance_eval do def human? true end end Person.human? # true class P end old_p = P.new P.class_eval do def pp p 'method pp' end end new_p = P.new old_p.pp # 'method pp' new_p.pp # 'method pp' old_p.class_eval do def old_pp p 'method old_pp' end end old_p.old_pp # 'method old_pp' new_p.old_pp # NoMethodError: undefined method 'old_pp' class P end obj_p = P.new P.instance_eval do def pp p 'method pp' end end P.pp # 'method pp' obj_p.pp # NoMethodError: undefined method 'pp' obj_p.instance_eval do def obj_p p 'method obj_p' end end obj_p.obj_p # 'method obj_p' P.obj_p # NoMethodError: undefined method 'obj_pp' obj_p.class_eval do def class_p p 'class_p' end end obj_p.class_p # 'class_p' P.class_p # NoMethodError: undefined method 'class_p' P.new.class_p # NoMethodError: undefined method 'class_p'

還可以這樣用
class Monk end Monk.instance_eval("def zen; 42; end", __FILE__, __LINE__) Monk.zen # 42
更詳細的資訊:

【下列文章您可能也有興趣】

沒有留言: