From: Peter Lane Date: 2011-12-09T01:57:03+09:00 Subject: Re: Confusing results from string multiplication The difference is down to the optional argument for Fixnum#to_s, the base for the string representation of the number: irb(main):026:0> 11.to_s(10) => "11" irb(main):027:0> 11.to_s(16) => "b" irb(main):028:0> 11.to_s(2) => "1011" Note the last one. Your '11.to_s *2' is being parsed as '11.to_s(2)' In the other two cases, Ruby is parsing the input as: '(11.to_s) * 2' to duplicate the string. "11" * 2 yields the same result, however you place the spaces. > 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 You have to be a little careful: whitespace matters in some cases to help separate tokens. For instance, you need a space or bracket before the argument to a method, else the method name cannot be separated from its argument: > 11.to_s10 NoMethodError: undefined method `to_s10' for 11:Fixnum from (irb):38 from /usr/local/bin/irb:12:in `
' irb(main):039:0> 11.to_s 10 => "11" The confusion here is that ' *2' has a special meaning as a token when used as the argument to a method, and this meaning does not arise in other 'multiplication' settings. Robert has just posted a nice explanation of that meaning. -- Posted via http://www.ruby-forum.com/.