Passing Multiple Arguments in Ruby: “*” is your friend 1

Posted by science on January 30, 2008

Arguments

Passing multiple arguments in Ruby is easy. You can pass any number of arguments, and even vary the class/types according to context. You can even vary the number of arguments passed. The receiver has to deal with this somehow, but even that’s pretty easy to manage. It’s a little trickier if the receiver has to delegate an unknown number of arguments to another receiver, but the * does the job for you – a great example of Ruby syntax that works for you. What follows is some simple example code to illustrate the idea.

def my_method(*args)
  # this line unrolls all the arguments out of the array
  # otherwise you'd be passing in an array to sub_method (see below)
  puts "Arguments received by sub_method as individual items:"
  sub_method(*args)
  # here we don't unroll the arguments so you can see the receiver
  # just gets an array instead of a series of arguments
  puts "Arguments received by sub_method as single array:"
  sub_method(args)
end

def sub_method(*args)
  args.each do |arg_item|
    puts arg_item.inspect
    puts arg_item.class.inspect
  end
end

my_method('1','2',3,[4,5,6])

Output is:


Arguments received by sub_method as individual items:
"1"
String
"2"
String
3
Fixnum
[4, 5, 6]
Array
Arguments received by sub_method as single array:
["1", "2", 3, [4, 5, 6]]
Array
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Lucas Renan Sat, 25 Sep 2010 09:43:09 UTC

    This tip is really helpful =)

Comments