m = 5*(
(1.0)
- (1.0/2.0)
)
puts m
m = 5*(
(1.0) - (1.0/2.0)
)
puts m
prints out:
bash-3.2$ ./run.rb
-2.5
2.5
The second result is what I expect, but I don't understand the first
result.
I usually put operands at the end of the line instead of the
beginning, so I never ran into this before, but this was originally
Python code that I converted into ruby.
This is the cause of the unexpected behavior. From what I can see, Ruby is interpreting the newline after (1.0) as a statement separator. Compare:
puts 5*(
(1.0);
- (1.0/2.0)
)
What's actually happening is that the third line (- (1.0/2.0)) is seen as a separate statement, not as a continuation on the second line. The minus sign in the beginning of the line is interpreted as the unary negation operator, not the binary (as in relating to two numbers, not one) subtraction operator.