tags:

views:

33

answers:

1

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!

+3  A: 

Module#define_method is private. Private methods can only be called without a receiver. So, in the second example, you need to use reflection (i.e. send) to circumvent the access restrictions.

Note that the first example still uses dynamic dispatch. In fact, in Ruby, everything (except variable access and some builtin operators) uses dynamic dispatch.

Jörg W Mittag