Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript-style `apply` in Ruby?

Tags:

ruby

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)
like image 399
Pat Newell Avatar asked Jul 03 '13 11:07

Pat Newell


2 Answers

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)
like image 53
samuil Avatar answered Nov 05 '22 13:11

samuil


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 >
like image 38
Ian Dickinson Avatar answered Nov 05 '22 14:11

Ian Dickinson