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?
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}."
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).
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):
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)
Just call it this way:
table_for(@things, *args)
The splat
(*
) operator will do the job, without having to modify the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With