赋值运算符和条件运算符的运算符优先级
我正在读一本关于 Ruby 1.8 和 1.9 的书,名为“The Ruby Programming Language”。书中说 if 运算符的优先级低于赋值运算符。如果这是真的,那么我不明白这个表达式是如何工作的:
如果为假,则 x = 5
如果赋值运算符具有更高的优先级,那么它应该在 if 运算符之前执行。因此,在执行 if false
之前,应将 5 赋给 x。
我是否误解了优先顺序?
I'm reading a book called "The Ruby Programming Language" for Ruby 1.8 and 1.9. The book says that if-operator has a lower precedence than an assignment-operator. If this is true then I don't understand how this expressions works:
x = 5 if false
If assignment-operator has a higher precedence then it should be executed before an if-operator. So, 5 should be assigned to x before if false
is executed.
Am I misunderstanding precedence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
较高的赋值优先级意味着表达式的计算结果为
(x = 5) if false
,而不是x = (5 if false)
。请注意,稍后也是一个完全有效的表达方式。每个特定子句是否被执行是由语言规则决定的。例如,在三元运算符
a ? b : c
,仅执行b
或c
,但不会同时执行两者。编辑
关于差异。
在
x = (5 if false)
中,首先处理赋值。但要完成它,我们需要赋值的左侧部分,即 nil,因为5 if false
的计算结果为nil
。因此,该表达式相当于 x = nil。在
(x = 5) if false
中,首先处理条件运算符。根据其规则,我们首先必须评估条件(false
)。由于它是false
,所以没有什么可做的,评估结果是nil
。希望这是清楚的。
Higher precedence of assignment means that your expression evaluates to
(x = 5) if false
, and not tox = (5 if false)
. Note, that later is a perfectly valid expression too.Whether each particular clause is executed is determined by language rules. E.g., in a ternary operator
a ? b : c
, onlyb
orc
will be executed, but not both.edit
About the difference.
In
x = (5 if false)
, assignment is processed first. But to complete it, we need left part of assignment, which isnil
, because5 if false
evaluates tonil
. So, the expression is equivalent ofx = nil
.In
(x = 5) if false
, conditional operator is processed first. According to its rules, we first have to evaluate condition (false
). Since it'sfalse
, there's nothing more to do and result of evaluation isnil
.Hope that's clear.
因为
; if
不是一个表达式。它是Ruby的一种特殊语法糖。它的工作原理如下:显然,
必须仅在
之后计算,因为
可以假
。Because
<expr> if <condition>
is not a one expression. It is a special syntaxic sugar of Ruby. It works just like:where, obviously,
<expr>
must be evaluated only after<condition>
because<condition>
can befalse
.