0
Optional parameters question.
SL gives an example of setting an optional parameter, but I can't figure out how to use the passed arguments in a computation. How do I loop through the array that contains the arguments? Example: if I pass two numbers, how do I square both of them? They would be part of an array if the parameter was (*x), correct? Now what? How do I pull each number and multiply it to itself? x*x, x*x and so on for each number passed as an argument to a method with an optional parameter.
3 odpowiedzi
+ 4
You can access the elements as you normally would with an array
For example, let's make a function that, if it only takes one argument, returns it, and if not it returns each number multiplied by the first argument
def some_func( x,*args)
if args.count != 0
args.each { | n | puts x * n }
else
puts x
end
end
some_func(5) #output: 5
some_func(2, 2, 4, 8) #output: 4, 8, 16
I use the count function to verify that args were not equal to nil, you could also have used something like the "any?" function
0
Thanks, Mickel.
I just got it to work with a case statement as you were answering. I will try your example as I think it allows for more flexibility with less code.
I had:
def sqr(*c)
x = c.length
case x
when 1
puts c[0]*c[0]
and so on, but doing it that way requires a WHEN for each number of arguments, sqr(#, #, #, ...).
Brain hurts.