From: Colin Bartlett Date: 2009-12-22T19:48:59+09:00 Subject: Re: Strange behavior of unary +@ for Fixnum? On Tue, Dec 22, 2009 at 3:45 AM, Caleb Clausen wrote: > On 12/21/09, Colin Bartlett wrote: >> Ruby parses (-7) as an _integer literal_, >> unless it's an expression like (-7**2) >> in which case it's parsed as (-(7**2)), that is (7**2).send( :-@ ) >> By analogy, it seems that the parser is treating (+7) as an integer literal, >> not as 7.send( :+@ ) ? > > This is correct. + or - at the start of an numeric literal is > tokenized as part of that literal. (Except in the ** case, as you say.) I think that your post is more correct than mine: when I put that bit about (-7**2) I was assuming (without trying) that (+7**2) would behave similarly. Not so, and your comment below about "+" being eaten up is correct. > The situation is somewhat better in 1.9, where at least >  + 7 #with a space in between > is treated as +@ method applied to the literal 7. But that doesn't > help in 1.8. Note that in ruby 1.8, any number of leading + signs are > glommed into the integer literal: > >  ++++++++++++++++++++++++++7  #still no method call in 1.8 > > Having integer literals eat up the leading + or - as part of the > number token is a common 'optimization' in many languages... When all else fails, actually try some code. Which is what I should have done before my first post. As confirmation of what you say in your post: # ruby=1.9.1 release-date=2009-07-16 platform=i386-mingw32 class Fixnum def +@() ; puts "in +@" ; self ; end def -@() ; puts "in -@" ; self * -1 ; end end -7 #=> -7 +7 #=> 7 -(7) #=> in -@ #=> -7 +(7) #=> in +@ #=> 7 -7**2 #=> in -@ #=> -49 +7**2 #=> 49 # note difference between this and -7**2 ---7 #=> in -@ #=> in -@ #=> -7 - 7 #=> in -@ #=> -7 +++7 #=> in +@ #=> in +@ #=> 7 + 7 #=> in +@ #=> 7 # ruby=1.8.6 release-date=2007-09-24 platform=i386-mswin32 # the only differences are, as you said: +++7 #=> 7 + 7 #=> 7