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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

Ruby handles multiple arguments well.

Here is a pretty good example.

def table_for(collection, *args)
  "Got #{collection} and #{args.join(', ')}"
end
table_for("one") » "Got one and " table_for("one", "two") » "Got one and two" table_for "one", "two", "three" » "Got one and two, three" table_for("one", "two", "three") » "Got one and two, three" table_for("one", ["two", "three"]) » "Got one and two, three"

(Output cut and pasted from irb)

Questions:
Answers:

Just call it this way:

table_for(@things, *args)

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

Questions:
Answers:
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