for instance in python it is possible to assign a method to a variable:
class MyClass
def myMethod(self):
return "Hi"
x = MyClass()
method = x.myMethod
print method() # prints Hi
I know this should be possible in Ruby, but I don’t know what’s the syntax.
You need to grab the method by using
methodwith the method’s name as an argument. This will return you an instance of typeMethod, which can be called withcall().Note that any arguments would need to be added to the
callmethod.In many practical cases, however, there is no need to have the method itself saved to a variable in Ruby; if you just want to dynamically call a method (i.e. send a message to an object) and there is no need to save the method, you could also use the
send(or__send__method in case of name clashes).Any arguments should follow the method name:
To use it like this is probably more Ruby-like, as the concept of Method classes is not as prominent as it is in Python. In Python, you can always think of a two step mechanism when doing something like
a_string.split(); first you grab the method witha_string.splitand then you call it (either implicitly with()or explicitly with__call__()). So, cutting that two-step mechanism is rather natural to do.Ruby is more based on message passing and to actually get a method class in Ruby, you’ll have to do some more work, because in some way, the method object will have to be constructed for you at that point. So, unless you really need some Methods object in Ruby, you should rather stick to the message passing abstraction and simply use
send.