简体   繁体   English

Ruby - 换行符和运算符

[英]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 . 正如您所期望的那样,输出为9 If you introduce a newline: 如果你引入换行符:

x = 4
y = 5
z = y
+ x

puts z

Then it outputs 5 . 然后输出5 This makes sense, because it's interpreted as two separate statements ( z = y and +x ). 这是有道理的,因为它被解释为两个单独的语句( z = y+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 . 输出为4 Why? 为什么?

(Disclaimer: I'm not a Ruby programmer at all. This is just a wild guess.) (免责声明:我根本不是Ruby程序员。这只是一个疯狂的猜测。)

With parens, you get z being assigned the value of 使用parens,可以为z赋值

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 输出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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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