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
更詳細的資訊:
- http://www.jimmycuadra.com/posts/metaprogramming-ruby-class-eval-and-instance-eval
- http://web.stanford.edu/~ouster/cgi-bin/cs142-winter15/classEval.php
- http://rubymonk.com/learning/books/5-metaprogramming-ruby-ascent/chapters/24-eval/lessons/67-instance-eval
- https://ruby-china.org/topics/2442
沒有留言:
張貼留言