Search code examples
rubyruby-1.9.2splat

Ruby to_s conversion to binary (Splat operator in argument)


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.


Solution

  • Right, as Namida already mentioned, Ruby interprets

    2.to_s *2
    

    as

    2.to_s(*2)
    

    as parentheses in method calls are optional in Ruby. Asterisk here is so-called splat operator.

    The only puzzling question here is why *2 evaluates to 2. When you use it outside of a method call, splat operator coerces everything into an array, so that

    a = *2
    

    would result with a being [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,

    2.to_s *2
    

    is essentially the same as

    2.to_s(2)