Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass multiple arguments to a ruby method as an array?

I have a method in a rails helper file like this

def table_for(collection, *args)  options = args.extract_options!  ... end 

and I want to be able to call this method like this

args = [:name, :description, :start_date, :end_date] table_for(@things, args) 

so that I can dynamically pass in the arguments based on a form commit. I can't rewrite the method, because I use it in too many places, how else can I do this?

like image 694
Chris Drappier Avatar asked May 06 '09 18:05

Chris Drappier


People also ask

How do you pass an array as a parameter in Ruby?

It is also possible to pass an array as an argument to a method. For example, you might want a method that calculates the average of all the numbers in an array. Your main program might look like this: data = [3.5, 4.7, 8.6, 2.9] average = get_average(data) puts "The average is #{average}."

What does * args mean in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

Can a method accept multiple parameters?

Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):


2 Answers

Ruby handles multiple arguments well.

Here is a pretty good example.

def table_for(collection, *args)   p collection: collection, args: args end  table_for("one") #=> {:collection=>"one", :args=>[]}  table_for("one", "two") #=> {:collection=>"one", :args=>["two"]}  table_for "one", "two", "three" #=> {:collection=>"one", :args=>["two", "three"]}  table_for("one", "two", "three") #=> {:collection=>"one", :args=>["two", "three"]}  table_for("one", ["two", "three"]) #=> {:collection=>"one", :args=>[["two", "three"]]} 

(Output cut and pasted from irb)

like image 148
sean lynch Avatar answered Sep 21 '22 01:09

sean lynch


Just call it this way:

table_for(@things, *args) 

The splat (*) operator will do the job, without having to modify the method.

like image 44
Maximiliano Guzman Avatar answered Sep 21 '22 01:09

Maximiliano Guzman