On 08.12.2011 17:16, Rob Marshall wrote:
> I thought, maybe this is a problem with irb, so I wrote a little
> program:
>
> #!/usr/bin/env ruby
>
> puts (11.to_s * 2)
> puts (11.to_s *2)
> puts (11.to_s*2)
>
> And when I run it, I see:
>
> 1111
> 1011
> 1111

but it works correctly for other numbers. try

puts (10.to_s *2)

;)

Well, it appears that "*2" becomes an argument to to_s, so your second 
line of code is interpreted as

puts (11.to_s(*2))

and this strange looking argument to to_s is actually interpreted as a 
splat operator and becomes converted to the Fixnum 2, so what you°«re 
actually requesting is a string containing the binary representation. 11 
as decimal is 0xb in hex or, as you see it, 1011 in binary.

There is quite some magic to splat operator°«s behavior in some cases. 
For example, the splat cannot stand on its own like a normal expression. 
So the following is invalid:

*[1,2]
*x
*2

but this is valid:

x=*[1,2]
y=*x
z=*2

Another magic  from my POV  is happening when assigning arrays to 
multiple variables. Splat doesn°«t seem to play a big role here, and 
sometimes it is hard to judge how such an assignment will end, 
considering differing data types on the RHS.

                       # actual              # expected
a=[1,2,3]             # a=[1,2,3]
b=*[1,2,3]            # b=[1,2,3]           # b=1
c,d=[1,2,3]           # c=1, d=2            # c=[1,2,3], d=nil
e,f=*[1,2,3]          # e=1, f=2
g,h=a                 # g=1, h=2            # g=[1,2,3], h=nil
a=2
i,j=a                 # i=1, j=2

> Can anyone explain why the '11.to_s *2' gave me 1011? Is this a 1.8.7
> problem? The Ruby version on my Mac OS X Lion system is: ruby 1.8.7
> (2010-01-10 patchlevel 249) [universal-darwin11.0].

Same here with 1.9.3-p0 Linux 64bit.

 Matthias