Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
slapthelownote Avatar asked Oct 01 '12 07:10

slapthelownote


1 Answers

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)
like image 69
Mladen Jablanović Avatar answered Sep 30 '22 12:09

Mladen Jablanović