72

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Chris Drappier
  • 5,280
  • 10
  • 40
  • 64

3 Answers3

100

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)

Stefan
  • 109,145
  • 14
  • 143
  • 218
sean lynch
  • 1,890
  • 1
  • 14
  • 5
  • There is a *very* similar example in [Programming Ruby, Thomas & Hunt, 2001](http://ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html) with a bit more explanation. See chapter "More About Methods", section "Variable-Length Argument Lists". – Jared Beck Feb 19 '13 at 19:53
69

Just call it this way:

table_for(@things, *args)

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

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Maximiliano Guzman
  • 2,035
  • 13
  • 14
  • 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)` – Paul Watson Jan 27 '22 at 11:03
0
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
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Anoob K Bava
  • 598
  • 7
  • 19
  • 2
    Could you also add an explanation? – Robert Jun 18 '15 at 09:45
  • 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 – Anoob K Bava Jun 19 '15 at 04:56
  • 1
    `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. – everm1nd Dec 14 '16 at 17:01