From: Dave Aronson Date: 2013-01-21T05:21:43+09:00 Subject: Re: question about string concatenation On Sun, Jan 20, 2013 at 3:08 PM, David Richards wrote: > I'm puzzled about why the following happens (I'm using v1.9.3): > > s = "[" 9.to_s "]" # error > > These other two concatenation constructs appear to work fine: > > s = "[" + 9.to_s + "]" > s = "[" << 9.to_s << "]" > > What's the key concept I'm missing here? Looks like you're trying to "autoconcatenate" three strings. (If that wasn't a word before, it is now!) This works fine IF they're all literals, like this: 1.9.3p194 :001 > "1" "2" "3" => "123" 1.9.3p194 :002 > "1" '2' "3" => "123" But if one of them is not a literal, Ruby won't autoconcatenate it: 1.9.3p194 :003 > "1" 2.to_s "3" SyntaxError: (irb):3: syntax error, unexpected tINTEGER, expecting $end "1" 2.to_s "3" ^ from /Users/dave/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `
' My SWAG would be that autoconcatenation takes place at the parser level, and using anything other than a literal would require actual evaluation, so it can't be done at that level, only after the thing is actually evaluated. At that level, though, it breaks the Ruby syntax rules, which require that you put some kind of operator between items. That's why your other examples *do* work, as you've inserted the + or << operators. -Dave -- Dave Aronson, the T. Rex of Codosaurus LLC, secret-cleared freelance software developer taking contracts in or near NoVa or remote. See information at http://www.Codosaur.us/.