15

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)
asked Jul 3, 2013 at 11:57
1
  • 2
    Your question seems to be very ambiguous. Could you refine it to point what would you like to accomplish? Do you want to change context of call? Do you want to change array into list of arguments? Do you want to call method which name is not known until runtime? Commented Jul 3, 2013 at 12:20

2 Answers 2

16

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)
answered Jul 3, 2013 at 12:02
Sign up to request clarification or add additional context in comments.

Comments

3

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 >
answered Jul 3, 2013 at 12:06

1 Comment

But can the arguments be passed as an array?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.