Are there equivalents to Ruby's method_missing in other languages?
Posted
by Justin Ethier
on Stack Overflow
See other posts from Stack Overflow
or by Justin Ethier
Published on 2010-05-19T13:26:30Z
Indexed on
2010/05/19
13:30 UTC
Read the original article
Hit count: 245
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?
© Stack Overflow or respective owner