Sunday, March 11, 2012

Ruby methods


Ruby provides way to call and define methods dynamically.
When you invoke a method, you actually send a message to an object. To illustrate this idea, let’s look at the following example.
class MyClass
  def greeting
    "Hello"
  end
end
obj = MyClass.new obj.greeting # => "hello"
obj.send :greeting # => "hello"
We can see that when you call greeting(), it actually goes through send() by sending the name of the method. This technique is called Dynamic Dispatch which means you can decide which method to call at runtime.
In Ruby, you also can define method dynamically with Module#define_method(). All you need to do is to pass a method name and a block.
class MyClass
  define_method :hello do
    "hello"
  end
end

obj = MyClass.new
puts obj.send :hello
With define_method(), we can define general-purpose method template to avoid duplicated code.
Another powerful thing in Ruby is method_missing(). With Ruby, there’s no compiler to check the method calls. So when you call a method that doesn’t existed, Ruby will finally call method_missing which raises NoMethodError. We can override method_missing() to handle no corresponding method. This is called Ghost Method since actually there is no corresponding method that exists.
class MyClass
  def method_missing(name, *args)
    puts "You tried to call #{name}, but this method is undefined"
  end
end

obj = MyClass.new
obj.hello   # => "You tried to call hello, but this method is undefined"

No comments:

Post a Comment