Saturday, January 27, 2007

Variable-length argument list

Ruby allows us to define a method with variable-length argument list by placing asterisk before array argument. When we call this method, arguments are placed as normal separated by colon but inside the method we got an array of arguments.
def varargs(*args)
  args.each {|arg| puts arg}
end

varargs()                # 
varargs('arg1')          # arg1
varargs('arg1', 'arg2')  # arg1 \n arg2

We can also do reversely, which mean to pass an array as parameter when calling a method and expand array inside the method.

def one(arg)
  puts "one argument: #{arg}"
end

def two(arg1, arg2)
  puts "two arguments: #{arg1}, #{arg2}"
end

def three(arg1, arg2, arg3)
  puts "three arguments: #{arg1}, #{arg2}, #{arg3}"
end

def call(method,*args)
  send(method,*args)  
end

call(:one,'1')                  # one argument: 1
call(:two,'1', '2')             # two arguments: 1,2
call(:three,'1', '2', '3')        # three arguments: 1,2,3

No comments: