Hal E. Fulton
2/27/2006 7:53:00 AM
Almann Goo wrote:
> Can someone please explain the semantics behind the following:
>
> irb(main):001:0> a = ( 4 + 5 )
> => 9
> irb(main):002:0> a = ( 4
> irb(main):003:1> + 5 )
> => 5
> irb(main):004:0> a = ( 4 +
> irb(main):005:1* 5 )
> => 9
>
> The first and last statements make sense to me, but why is the second one
> returning 5?
>
> I find semantics like this troubling, and no documentation sheds light as
> to what would cause this behavior.
I understand your concern. Let me try to clarify.
Expressions in Ruby can be like standalone statements. Statements are
terminated with an optional semicolon or with a newline. If a statement
is incomplete, it is understood to go on to the next line; if it is
complete, it is just as if terminated with a semicolon.
Therefore:
a = (4
+5)
is the same as
a = (4;
+5)
or even
a = (4; +5)
That is, it evaluates a "4" and then evaluates a "+5" (which then is the
resultant value, as it was the last evaluated).
But with
a = (4+
5)
the parser is able to see that the expression is not complete, and is
apparently continued on the next line.