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