我是 Ruby 元编程的初学者。在 irb 中练习我的代码时,我遇到了这个问题。
class A; end
a = A.new
b = class << a; self; end
b.instance_eval { def foo; puts 'foo'; end }
# => works for b.foo
b.instance_eval { define_method :bar do; puts 'bar'; end }
# => WHY this one works for a.bar rather than b.bar
最后一个代码片段让我很困惑。
感谢您的具体回答,但也许我没有清楚地解释我的困惑。我真正想了解的是为什么define_method
在这些情况下表现如此不同,这里:
class A
def foo1
p 'foo1 from A'
end
define_method :bar1 do
p 'bar1 from A'
end
end
a = A.new
a.foo1 # => 'foo1 from A'
a.bar1 # => 'bar1 from A'
a.instance_eval { def foo2; p 'foo2 from a.metaclass'; end }
a.foo2 # => 'foo2 from a.metaclass'
a.instance_eval { define_method :bar2 do; p 'bar2 from a.metaclass'; end }
# => NoMethodError: undefined method `define_method' for #<A:0x000000016a2e70>
aa = class << a; self; end
aa.instance_eval { def foo3; p 'foo3 from a.metaclass.metaclass'; end }
aa.foo3 # => 'foo3 from a.metaclass.metaclass'
aa.instance_eval { define_method :bar3 do; p 'bar3 from a.metaclass.metaclss'; end }
aa.bar3 # => NoMethodError: undefined method `bar3' for #<Class:#<A:0x000000016a2e70>>
a.bar3 # => 'bar3 from a.metaclass.metaclss'
我知道这不会出现在日常编码中,但我想让我的想法清晰。
做一个结论:
aa = class << a; self; end
aa.instance_eval { def foo; puts 'foo..'; end }
# defines a singleton-method for aa
aa.foo # => 'foo...'
aa.instance_eval { define_method :bar do; puts 'bar..'; end }
# equals
aa.class_eval { def bar; puts 'bar..'; end }
# both define a singleton-method for a,
# as define_method and class_eval both define instance_method
a.bar # => 'bar...'