Alex Rivera | Logout

Are there equivalents to Ruby's method_missing in other languages?

Asked 2010-05-19T13:26:30.313
23

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

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. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

class Roman
 def romanToInt(str)
   # ...
 end
 def method_missing(methId)
   str = methId.id2name
   romanToInt(str)
 end
end

r = Roman.new
r.iv      #=> 4
r.xxiii   #=> 23
r.mm      #=> 2000

For example, Ruby on Rails uses this to allow calls to methods such as find_by_my_column_name.

My question is, what other languages support an equivalent to method_missing, and how do you implement the equivalent in your code?

Edit
Report

2 Answers

5

C# now has TryInvokeMember, for dynamic objects (inheriting from DynamicObject)

answered 2010-05-20T02:55:31.083
2

Tcl has something similar. Any time you call any command that can't be found, the procedure unknown will be called. While it's not something you normally use, it can be handy at times.

answered 2010-05-19T14:12:31.150

Your Answer