Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method_missing in "Programming Ruby" over my head

method_missing

*obj.method_missing( symbol h , args i ) → other_obj

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values. A more typical use of method_missing is to implement proxies, delegators, and forwarders.

class Roman
  def roman_to_int(str)
    # ...
  end
  def method_missing(method_id)
    str = method_id.id2name
    roman_to_int(str)
  end
end
r = Roman.new
r.iv ! 4
r.xxiii ! 23
r.mm ! 2000

I just heard about method-missing and went to find out more in Programming Ruby but the above explanation quoted from the book is over my head. Does anyone have an easier explanation? More specifically, is method-missing only used by the interpreter or is there ever a need to call it directly in a program (assuming I'm just writing web apps, as opposed to writing code for NASA)?

like image 989
j. parks Avatar asked Aug 09 '26 12:08

j. parks


1 Answers

It's probably best to not think of ruby as having methods. When you call a ruby "method" you are actually sending a message to that instance (or class) and if you have defined a handler for the message, it is used to process and return a value.

So method_missing is a special definition that gets called whenever ruby cannot find an apropriate handler. You could also think of it like a * method.

like image 198
Samuel Avatar answered Aug 11 '26 06:08

Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!