From: Robert Klemme Date: 2011-12-09T01:32:38+09:00 Subject: Re: Confusing results from string multiplication On Thu, Dec 8, 2011 at 5:16 PM, Rob Marshall wrote: > Hi, > > I actually registered here to ask a different question, but after > checking the core docs for 1.8.7 I realized that the behavior has > apparently changed, but as part of the registration process I was asked > to enter the result of: > > puts ((11.to_s * 2).to_i/2) > > I don't know Ruby very well, but this one seemed pretty > straight-forward, in that it was supposed to convert the number (object) > 11 to a string, double it ('1111') then convert it back to an integer > and divide by two. Since these are integers the answer would be: 555. > > But here's where it gets strange. Since I'm new to Ruby I thought I'd > play with it a bit, and since I thought that whitespace wasn't supposed > to matter, I did: > >>> 11.to_s * 2 > => "1111" >>> 11.to_s *2 > => "1011" >>> 11.to_s*2 > => "1111" > > 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 > > 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]. Congratulations, you really hit a strange corner case in the syntax! irb(main):003:0> 11.to_s *2 => "1011" irb(main):004:0> 11.to_s(*2) => "1011" irb(main):005:0> 11.to_s(2) => "1011" The variant with a single space before the star and no space after is actually the splash operator as in: irb(main):011:0> def f(*a) p a end => nil irb(main):012:0> args = [1,2,3] => [1, 2, 3] irb(main):013:0> f(args) [[1, 2, 3]] => [[1, 2, 3]] irb(main):014:0> f(*args) [1, 2, 3] => [1, 2, 3] irb(main):015:0> f(args, 77, 88) [[1, 2, 3], 77, 88] => [[1, 2, 3], 77, 88] irb(main):016:0> f(*args, 77, 88) [1, 2, 3, 77, 88] => [1, 2, 3, 77, 88] In your case: irb(main):017:0> def f(a) p a end => nil irb(main):018:0> f(2) 2 => 2 irb(main):019:0> f(*2) 2 => 2 And 11.to_s(2) ist just the conversion to binary: irb(main):021:0> 11.to_s 2 => "1011" irb(main):022:0> 11.to_s 10 => "11" irb(main):023:0> 11.to_s 16 => "b" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/