For methods in Ruby, is there anything similar to javascript's apply
?
That is, if some method were defined to take a few parameters, say, some_method(a, b, c)
and I have an array of three items, can I call some_method.apply(the_context, my_array_of_three_items)
?
EDIT: (to clear up some confusion): I don't care so much about the context of the call, I just want to avoid this:
my_params = [1, 2, 3]
some_method(my_params[0], my_params[1], my_params[2])
instead, I'm curious to know if there is something like this
my_params = [1, 2, 3]
some_method.apply(my_params)
There are bindings which are closest counterpart of javascript context, and there are unbound methods which can be later bound to object to be called in it's scope.
Bindings must be earlier captured, and they allow evaluating code from string in it's context.
Unbinding method captured from any object with method extractor allows you to later bind it to an object (note that it must share enough of interface for method to work) and call it in it's scope.
Unless you want to hack some very low-level things in Ruby, I would discourage use of both of above in favor of object-oriented solution.
EDIT:
If you simply want to call method, while it's arguments are contained in array use splat operator:
a = [1, 2, 3]
method(*a)
You can invoke a method whose name is only known at run-time by the send
method on Class
.
Update
To pass the arguments as an array:
$ irb
2.0.0p195 :001 > class Foo
2.0.0p195 :002?> def bar( a, b, c)
2.0.0p195 :003?> puts "bar called with #{a} #{b} #{c}"
2.0.0p195 :004?> end
2.0.0p195 :005?> end
=> nil
2.0.0p195 :006 > foo = Foo.new
=> #<Foo:0x000000022206a8>
2.0.0p195 :007 > foo.bar( 1, 2, "fred" )
bar called with 1 2 fred
=> nil
2.0.0p195 :009 > foo.send( :bar, *[1, 2, "jane"] )
bar called with 1 2 jane
=> nil
2.0.0p195 :010 >
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