开发者

Date Increment Issue

-> irb
>> (Date.today +3).to_s
=> "2009-10开发者_如何学JAVA-22"
>> (Date.today + 3).to_s
=> "2009-10-25"

between "+3" and "+ 3", there is a difference?


"+3" with no space means positive 3, which gets passed to the today method as an argument, while "+ 3" means plus three, so the return value of the today method gets added to 3.

In case you're curious, the optional parameter to the today method "specifies the Day of Calendar Reform", for conversions to other date formats.


I realize this must have been a frustrating bug to discover. When using a language where method invocation has optional parentheses, whitespace is a delicate matter. Consider the following:

square(2+2)*2   # square(4)*2 = 16*2 = 32
square (2+2)*2  # square(4*2) = square(8) = 64

Your case is trickier because the +3 with no space is actually a unary operator. ! ~ and + unary operators have the highest precedence.

Also interesting the - unary operator has a lower precedence than the exponentiation operator. Therefor

-4**2  # -(4**2) = -16


It seems to me that the + binds to the 3 in the first case. That is the interpreter sees Date.today(+3). If there's a space after the plus the interpreter instead sees (Date.today) + (3).

Using + to denote positive numbers isn't very common since numbers are positive to begin with, but consider the case of negative numbers: it's easier to see that Date.today -3 means something else than Date.today - 3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜