I’m a start learner about Ruby MetaProgramming. when practicing my code in irb, I met this problem.
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
The last code fragment confused me.
Thanks for your specific answers, but maybe I didn’t explain my confusion clearly. What I’m really trying to understand is why define_method behaves so differently in these cases, here:
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'
I know that this doesn’t come up in day-to-day coding, but I want to make my mind clear.
make a conclusion:
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...'
In addition to all other comments :
[from the Pickaxe] The method Object#instance_eval lets you set self to be some arbitrary object, evaluates the code in a block with [self], and then resets self.
And Module#define_method : Defines an instance method in the receiver [self, which must be a (anonymous) Class or Module].
define_method :bar3is executed in the context of singleton_class_of_object_a (an anonymous class, see below), thus defines an instance method of that class, hence bar3 becomes a singleton method of a. As already said in my previous answer, it is equivalent to defining directly on the object :After
a = A.new, the field class of instance a points to class A.With
class << aordef a.bar4, Ruby creates an anonymous class, the field class of instance a now points to this anonymous class, and from there to A.Methods defined in this context with
defordefine_methodgo into the methods table of the anonymous class.