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

Ruby on-RailsRubyArraysMethodsArguments

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Ruby handles multiple arguments well.

https://web.archive.org/web/20170113103604/http://www.misuse.org/science/2008/01/30/passing-multiple-arguments-in-ruby-is-your-friend">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 - Ruby on-Rails

Just call it this way:

table_for(@things, *args)

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

Solution 3 - Ruby on-Rails

class Hello
  $i=0
  def read(*test)
	$tmp=test.length
	$tmp=$tmp-1
	while($i<=$tmp)
      puts "welcome #{test[$i]}"
	  $i=$i+1
	end
  end
end

p Hello.new.read('johny','vasu','shukkoor')
# => welcome johny
# => welcome vasu
# => welcome shukkoor

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris DrappierView Question on Stackoverflow
Solution 1 - Ruby on-Railssean lynchView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMaximiliano GuzmanView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAnoob K BavaView Answer on Stackoverflow