If I run the following code, the first two lines return what I expect. The third, however, returns a binary representation of 2.
2.to_s # => "2"
2.to_s * 2 # => "22"
2.to_s *2 # => "10"
I know that passing in 2 when calling to_s will convert my output to binary, but why is to_s ignoring the * in the third case? I’m running Ruby 1.9.2 if that makes any difference.
Right, as Namida already mentioned, Ruby interprets
as
as parentheses in method calls are optional in Ruby. Asterisk here is so-called splat operator.
The only puzzling question here is why
*2evaluates to2. When you use it outside of a method call, splat operator coerces everything into an array, so thatwould result with
abeing[2]. In a method call, splat operator is doing the opposite: unpacks anything as a series of method arguments. Pass it a three member array, it will result as a three method arguments. Pass it a scalar value, it will just be forwarded on as a single parameter. So,is essentially the same as