When I define a method inside instance_eval block for class it creates a class method which is fine.
Eg)
class A
end
A.instance_eval do
def method; end
end
A.method #works
But when I use define_method inside instance_eval it creates instance method instead of class method Eg)
A.instance_eval do
define_method(:method1) {}
end
A.method1 # NoMethodError: undefined method `method1'
A.new.method1 # Works fine
I am unable to understand above phenomena. Please can somebody help me out.
This quirky behavior makes a little more sense if you look at
instance_eval
in the context of instances (which is its main purpose).Where is
foo
defined? The only sensible place I can think of isa
's singleton class, and indeed that is trueSo this demonstrates the rule
which is completely consistent with what you saw.
So why does
define_method
behave differently? Because unlikedef
it's a method! So thisis really just
which is the metaprogramming way of creating normal instance methods. This inconsistency may seem annoying, but again look at the case for normal instances and you'll see why
def
anddefine_method
can't be consistent. Thisis really just
which is nonsense