Sunday, September 21, 2008

Variable Parameters

Sometimes we want a method that can take any number of parameters.
One way to do it is to pass in a hash, but this can be annoying. Another method is to put an * before the method's parameter. Within the body of the method, list will be treated as an array with 0 or more elements.

For example:

def average(*list)
x = 0
list.each {|l| x+= l}
l/list.size
end

irb>average 1,2,3,4,5,6,7,8,9
=> 5

J

No comments: