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.
Comments
-
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 over 11 yearsThere 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 about 10 yearsThis was exactly what I was looking for.
-
Robert about 9 yearsCould you also add an explanation?
-
Anoob K Bava about 9 yearsfirst 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 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 ofread
function will never work. -
Paul Watson over 2 yearsI was trying to compose parameters for a fixed method from an array and your answer helped thanks e.g.;
method(*['a', '', nil].compact_blank)