Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - newlines and operators

Tags:

operators

ruby

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?

like image 745
mopoke Avatar asked Feb 11 '10 01:02

mopoke


2 Answers

(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.

like image 184
Anon. Avatar answered Sep 28 '22 10:09

Anon.


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.

like image 40
Kevin Avatar answered Sep 28 '22 09:09

Kevin