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

103,443

Solution 1

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)

Solution 2

Just call it this way:

table_for(@things, *args)

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

Share:
103,443
Chris Drappier
Author by

Chris Drappier

I'm a ruby on rails developer with Phishme, Inc.

Updated on July 05, 2022

Comments

  • Chris Drappier
    Chris Drappier almost 2 years

    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?

  • Jared Beck
    Jared Beck over 11 years
    There is a very similar example in Programming Ruby, Thomas & Hunt, 2001 with a bit more explanation. See chapter "More About Methods", section "Variable-Length Argument Lists".
  • Pelle
    Pelle about 10 years
    This was exactly what I was looking for.
  • Robert
    Robert about 9 years
    Could you also add an explanation?
  • Anoob K Bava
    Anoob K Bava about 9 years
    first of all, create a pointer test,which is like an array,then, find the array length. then we have to iterate the loop till the counter reaches the length.then in loop it will print the welcome message with all the arguements in method
  • everm1nd
    everm1nd over 7 years
    i is defined here as global variable. it will be set to zero only once, when class is loaded. so second run of read function will never work.
  • Paul Watson
    Paul Watson over 2 years
    I was trying to compose parameters for a fixed method from an array and your answer helped thanks e.g.; method(*['a', '', nil].compact_blank)