Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an array of arguments, how do I send those arguments to a particular function in Ruby?

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 with a 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 to call but converts the array into an argument list.

like image 849
Steven Avatar asked Jan 10 '11 02:01

Steven


People also ask

How an array can be passed to a function as an argument?

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.

How do you pass an argument in Ruby?

In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

What do you pass to a function to pass an array as an argument to a function quizlet?

To pass an array as an argument to a function, pass the name of the array. Quite often, you'll want to write functions that process the data in arrays.


1 Answers

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) 
like image 100
sepp2k Avatar answered Oct 11 '22 00:10

sepp2k