0

i don't understand. this one works:

class Foo
  def initialize(*args)
    @variables = *args unless args[0].eql?(nil)
  end
end

this one don't:

class Foo
  def initialize(*args)
    args[0].eql?(nil) ? @multiples = [3,5] : @multiples = *args
  end
end

but this one works too:

class Foo
  def initialize(*args)
    args[0].eql?(nil) ? @multiples = [3,5] : @multiples = args
  end
end

my question is about 'args' and '*args' between the second form and the third. why is that ?

jc newb
  • 5
  • 3

1 Answers1

2

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
daremkd
  • 8,244
  • 6
  • 40
  • 66
  • in fact there is a 'collision' with the splat operator: in method definition is for capturing multiple arguments and in the body method is for multiply ? thats right ? – jc newb Oct 22 '14 at 12:07
  • Well it's used for multiple purposes in the method body, see http://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/ and I'm supposing this error was due to some 'collision' yes. The splat can be very useful when used properly in a method body, see this article for some examples. – daremkd Oct 22 '14 at 12:10
  • and nice tip for nil. is an object too. everything is object in Ruby. hard concept to grasp for a noob. thaks again ;) – jc newb Oct 22 '14 at 12:14