tags:

views:

98

answers:

3
-> irb
>> (Date.today +3).to_s
=> "2009-10-22"
>> (Date.today + 3).to_s
=> "2009-10-25"

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

A: 

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.

Theo
The grammar probably has some rule where `value := augmentor number` and `augmentor` is allowed to be `+`, `-` or `empty`. This is just supposition, I haven't actually followed up on it...
ezpz
+4  A: 

"+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.

wdebeaum
the problem is, how do i know if a method accepts parameter or not? I would have been careful if i knew .today can have optional parameters
penger
There are at least three ways to check if a method accepts a parameter: (1) look at the documentation for that method, (2) try giving it one, and see if you get an error, or (3) use the "arity" method on the method object, like so: Date.method("today").arity => -1 (-1 means it takes a variable number of arguments; otherwise arity returns the fixed number of arguments expected).Furthermore, if the "today" method didn't actually accept an argument, you would get an error from (Date.today +3), because it would still try to pass +3 as an argument rather than try to add 3 to the result.
wdebeaum
Sorry, I just checked the docs and arity can actually return other negative numbers: if a method requires at least n arguments, but allows additional arguments, then arity returns -n-1.
wdebeaum
+1  A: 

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
avguchenko
frustrating? Hells yea, if it wasn't for debugger, I will never discover the bug because at a glance it is not obvious at all
penger