Saturday, May 10, 2014

#method_missing

method_missing in ruby is a really interesting and powerful concept. Inside of every Class you create in ruby you have the ability to override #method_missing to do whatever you would like it to do. Here is an example:

class Person
  def walk
    puts "I'm walking"
  end

  def method_missing(sym, *args)
    puts "Looks like you can't do this"
  end
end

person = Person.new
person.walk #=> "I'm Walking"
person.fly #=> "Looks like you can't do this"

When person.fly was called ruby looked for the method fly and realized that it did not exist. Instead of throwing an error we had created our own #method_missing so when a method does not exist it puts the string in the method. 

This can be used in many more ways than such an elementary example such as metaprogramming, observer patterns, etc, but you can get the point of the power of something like this.

No comments:

Post a Comment