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

Chris Drappier picture Chris Drappier · May 6, 2009 · Viewed 97.2k times · Source

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?

Answer

sean lynch picture sean lynch · May 6, 2009

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)