Im reading Metaprogramming in Ruby.
Here are two code snippets from the book:
my_var = "Success"
MyClass = Class.new do
puts "#{my_var} in the class definition!"
define_method :my_method do
puts "#{my_var} in the method!"
end
end
MyClass.new.my_method
⇒ Success in the class definition!
Success in the method!
and:
def define_methods
shared = 0
Kernel.send :define_method, :counter do
shared
end
Kernel.send :define_method, :inc do |x|
shared += x
end
end
define_methods
counter # => 0
inc(4)
counter # => 4
I wonder why one doesnt have to use dynamic dispatch (use of Kernel.send) when defining the method in the first example while one has to use it in the second example.
I given it some thoughts but cant understand it.
Thanks!