在 Ruby 中赋值是否在逻辑运算符之前? [英] Does assignment precede logical operator in Ruby?
问题描述
我在 Ruby 的 if
条件中遇到了一个奇怪的情况.这是重现这种情况的示例代码.
I have encountered a strange situation in the if
condition of Ruby. Here is the sample code to reproduce the situation.
p1 = /hello/
p2 = /world/
s = "hello, world"
if m1 = s.match(p1) && m2 = s.match(p2)
puts "m1=#{m1}"
puts "m2=#{m2}"
end
输出将是
m1=world
m2=world
但我期望 m1=hello
因为 &&
操作符具有 更高的优先级 Ruby 运算符.
But I expected m1=hello
because the &&
operator has higher precedence in Ruby operators.
此代码
if m1 = s.match(p1) && m2 = s.match(p2)
似乎被解释为
if m1 = (s.match(p1) && m2 = s.match(p2))
为什么逻辑 AND 运算符 &&
在赋值运算符 =
之前?
Why is the logical AND operator &&
preceded over the assignment operator =
?
推荐答案
在 ruby 中,几乎所有东西(见评论)都会返回一个值.
In ruby, pretty much everything (see comments) returns a value.
运算符 &&
返回其右侧的最后一个表达式.所以 1 &&3
产生 3. &&
将在第一个 falsey 值上短路.它返回该值,或最后计算的真值表达式.
The operator &&
returns the last expression to its the right. So 1 && 3
yields 3. &&
will short circuit on the first falsey value. It returns either that value, or the last evaluated truthy expression.
||
返回其左侧的第一个表达式 - 所以 1 ||3
产生 1.||
将短路第一个真值,返回它.
||
returns the first expression to the its left - so 1 || 3
yields 1. ||
will short circuit on the first truthy value, returning it.
检查这个差异:
1 + 5 * 3 + 1
# => 17
1 + 5 && 3 + 1
# => 4
1 + 5 || 3 + 1
# => 6
这是m1 = s.match(p1) && 中的求值顺序m2 = s.match(p2)
s.match(p1)
=>你好"&&
=>正确评估一切m2 = s.match(p2)
=>世界"m1 = "你好";&&世界"
=>世界"
s.match(p1)
=> "hello"&&
=> evaluate everything to its rightm2 = s.match(p2)
=> "world"m1 = "hello" && "world"
=> "world"
您对 m2
的赋值返回用于 &&
表达式world"的第二部分的值.ruby 中的赋值也返回一个值!
Your assignment to m2
returns the value which is used for the second part of the &&
expression, "world". Assignments in ruby also return a value!
所以你将有 m1 和 m2 的值都为world".
So you will have m1 and m2 both with the value "world".
这篇关于在 Ruby 中赋值是否在逻辑运算符之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!