tags:

views:

88

answers:

3

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?

+10  A: 

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

Anon.
+1. I was trying to explain the basic concept of unfinished commands when I realized that the output was 4, not 9. Good going :)
Matchu
That makes lots of sense. I was coming from the same example in Scala where it treats it as z = (y+x) and outputs 9. Good explanation :-)
mopoke
Multiline parentheses are essentially a block, and the block's value is the last statement in it.
kejadlen
+4  A: 

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.

Kevin
+2  A: 

Well you won't need the escaping character \ if your lines finishes with the operator

a = 4
b = 5
z = a +
    b

puts z 
# => 9
Roman Gonzalez
I use this technique to end a line with a dot if I'm chaining together a bunch of methods.
glenn jackman
Yes, is the best way to break long lines of code
Roman Gonzalez