Sam Smoot
4/7/2007 2:34:00 AM
On Apr 6, 12:21 pm, srinsri...@gmail.com wrote:
> I just noticed that whitespace near the -1 makes a difference in the
> evaluation in irb. is this expected?
>
> irb(main):006:0> (Date.today -1).to_s
> => "2007-04-06"
>
> irb(main):008:0> (Date.today - 1).to_s
> => "2007-04-05"
Yes. "-1" is "negative one", "- 1" is "minus one". So the former is
interpreted as passing the value -1 to the method
Date::today(sg=ITALY), while the latter is interpreted as calling
Date#- on the instance returned from Date::today and passing 1 as the
parameter to Date#-.
So it just goes to show, spacing matters, so better to be clear than
invalid.
If you think about it, if the left-hand-side contains a ".", so a
method call, the language parser can't interpret what you mean in this
example without giving significance to the whitespace.
If you try the same without a trailing method on the LHS, for example
"1 -1", then just like in math, the meaning becomes unambiguos, since
without interpreting the minus symbol as a call to Fixnum#-, there is
no expression, and the line would otherwise just be a syntax error.
So the parser is forgiving when it can be I suppose. Me, I prefer to
just use whitespace always unless I mean to actually represent a
negative number. To do otherwise just feels sloppy to me. :-)