Given an array of arguments, how do I send those arguments to a particular function in Ruby?
24,356
As you know, when you define a method, you can use the *
to turn a list of arguments into an array. Similarly when you call a method you can use the *
to turn an array into a list of arguments. So in your example you can just do:
Ilike.new.turtles(*a)
Author by
Steven
Updated on July 05, 2022Comments
-
Steven about 2 years
Forgive the beginner question, but say I have an array:
a = [1,2,3]
And a function somewhere; let's say it's an instance function:
class Ilike def turtles(*args) puts args.inspect end end
How do I invoke
Ilike.turtles
witha
as if I were calling(Ilike.new).turtles(1,2,3)
.I'm familiar with
send
, but this doesn't seem to translate an array into an argument list.A parallel of what I'm looking for is the Javascript
apply
, which is equivalent tocall
but converts the array into an argument list. -
Steven over 13 yearsFantastic. Based on your excellent answer, I've found a more thorough account of this technique in Wikibooks. This is actually perfectly reasonable given the parallel notation going the other other way. Oh, Ruby indeed. I've also noticed that you can prepend your own arguments without awkward
a.unshift
fidgeting by usingIlike.new.turtles(1,2,3,*a)
, although postpending seems to require such a manoeuver. -
Phrogz over 13 years@StevenXu In Ruby 1.9 you can also splat for 'postpending'.
a=[1,2]; b=[4,5]; p(0,*a,3,*b,6) #=> "0\n1\n2\n3\n4\n5\n6"
-
RubyFanatic about 10 yearsFantastically answered!
-
SourceSeeker almost 5 yearsThis is a fun technique:
some_func(*'some string of args'.split)