Convert Ruby to_s to binary (Splat operator in argument)

If I run the following code, the first two lines will return what I expect. The third, however, returns binary representation 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 converts my output to binary, but why does to_s ignore * in the third case? I am running Ruby 1.9.2 if that matters.

+4
source share
2 answers

That's right, as Namida has already mentioned, Ruby interprets

 2.to_s *2 

a

 2.to_s(*2) 

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

The only mysterious question: why *2 is evaluated as 2 . When you use it outside of a method call, the splat operator forces everything to an array, so

 a = *2 

will cause a to be [2] . In a method call, the splat operator does the opposite: decompresses something as a series of method arguments. Pass it an array of three elements, this will be the result in the form of three method arguments. Pass it a scalar value, it will just be redirected as one parameter. In this way,

 2.to_s *2 

essentially coincides with

 2.to_s(2) 
+5
source

On the third line, you call the to_s method with a "splat" of 2, which evaluates to 2 (in the method call) and therefore returns a number in another database .

0
source

Source: https://habr.com/ru/post/1437123/


All Articles