简体   繁体   中英

Ruby - newlines and operators

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM