Ghost Methods in Ruby (transfer)
1 year, 7 months ago
I bring to your attention transfer of a fragment of the book Metaprogramming Ruby 2 behind authorship Paolo Perrotta (Paolo Perrotta).
What is method_missing?
In Ruby we can call methods which do not exist, but it will return us an error. For an example:
class Lawyer; end
nick = Lawyer.new
nick = talk_simple
NoMethodError: undefine method 'talk_simple' for #<Lawyer:0x007f801aa81938>
Whether you remember as search of methods works? When you call the method talk_simple, Ruby goes to object class of nick, and touches methods there. If it cannot find a method there, he looks for it in parents of this class, then in Object and at last in BasicObject. Well and as Ruby cannot find the talk_simple method anywhere, it starts the method_missing method for nick’a. Ruby knows that this method is because it is the private BasicObject method from which all objects are inherited.
Read more »