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.
In Ruby, "pass by object reference" (to use Python's terminology) is used: Inside the function, any of the object's members can have new values assigned to them and these changes will persist after the function returns.
The ruby equivalent of this is self - they both refer to the current instance. The tricky part is that in Ruby class scope, self refers to the current instance of the class Class that defines the class you are building. Inside a method, self refers to the instance of the class.
You need to grab the method by using method
with the method’s name as an argument. This will return you an instance of type Method
, which can be called with call()
.
class MyClass def myMethod "Hi" end end x = MyClass.new m = x.method(:myMethod) # => #<Method: MyClass#myMethod> puts m.call # You can also do m[] instead of m.call()
Note that any arguments would need to be added to the call
method.
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).
x = MyClass.new puts x.send :myMethod # also possible with a string: m.send "myMethod" # "Hi"
Any arguments should follow the method name:
puts x.send(:myMethod, arg1, arg2)
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 with a_string.split
and 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
.
I think you are looking for Proc or lambda block
x = Proc.new { return "Hello World" } puts x.call x = lambda { return "Hello World" } puts x.call
I would read this short post - there is a slight but significant difference in the way the methods behave http://samdanielson.com/2007/3/19/proc-new-vs-lambda-in-ruby
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With