The splat operator (the star *), as you know, when used in method definitions, will capture an unlimited number of arguments and convert them to an array. However, its purpose IS DIFFERENT when used in a METHOD body. There's no point of putting the splat * in a method body when doing an assignment because
a) You'll get the same result as if you didn't put it.
class Foo
def initialize(*args)
@a = args
@b = *args
p @a == @b
end
end
Foo.new(1,2,3) #=> prints 'true'
b) You'll get strange errors like in your second example which probably produces an error because Ruby confuses the precedence of the operators. It will work if you put parentheses around the whole expression, however:
class Foo
def initialize(*args)
args[0].eql?(nil) ? @multiples = [3,5] : (@multiples = *args)
end
end
So to sum up, when doing an assignment of a splat to a variable, don't use the * .
Btw, a bit off topic, instead of doing args[0].eql?(nil)
, you can just do arg[0].nil?
Also, instead of assigning @multiples twice, you can do something like:
@multiples = args[0].nil? ? [3,5] : args