Consider the following code:
x = 4
y = 5
z = (y + x)
puts z
As you'd expect, the output is 9
. If you introduce a newline:
x = 4
y = 5
z = y
+ x
puts z
Then it outputs 5
. This makes sense, because it's interpreted as two separate statements (z = y
and +x
).
However, I don't understand how it works when you have a newline within parentheses:
x = 4
y = 5
z = (y
+ x)
puts z
The output is 4
. Why?
(Disclaimer: I'm not a Ruby programmer at all. This is just a wild guess.)
With parens, you get z
being assigned the value of
y
+x
Which evaluates to the value of the last statement executed.
End the line with \ in order to continue the expression on the next line. This gives the proper output:
x = 4
y = 5
z = (y \
+ x)
puts z
outputs 9
I don't know why the result is unexpected without escaping the newline. I just learned never to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With