我不理解 Ruby 文档中在 if 表达式中赋值的代码
I don't understand the code in Ruby documentation that assigns a value within an if expression
Ruby 文档说:
if a = object.some_value #assigns a value
# do something to a
end
但是当运行上面的代码时我得到一个警告:
warning: found = in conditional, should be ==
这意味着示例实际上应该是:
if a == object.some_value
# do something to a
end
可以给if
中的变量赋值吗?
这两段代码在视觉上相似,但意图却大不相同。第一个是这样写的:
# Run object.some_value and capture the result into a
if a = object.some_value
# ...
end
第二个是这样写的:
# If a is equivalent to the result of object.some_value
if a == object.some_value
# ...
end
这是比较 ==
。
捕获形式经常用于各种情况,有时是字面上的 case
,例如您捕获笨拙 and/or 缓慢代码块的结果的地方:
case (name = professor.name.to_s.split(/\s+/).last)
when "O'Reilly", "Berners-Lee"
puts "Prof. %s is invited to the party." % name
else
puts "Prof. %s is not invited to the party."
end
其中 =
是有意分配的,因此您可以从那时起参考 name
而不必重新计算该块。
Ruby 文档说:
if a = object.some_value #assigns a value
# do something to a
end
但是当运行上面的代码时我得到一个警告:
warning: found = in conditional, should be ==
这意味着示例实际上应该是:
if a == object.some_value
# do something to a
end
可以给if
中的变量赋值吗?
这两段代码在视觉上相似,但意图却大不相同。第一个是这样写的:
# Run object.some_value and capture the result into a
if a = object.some_value
# ...
end
第二个是这样写的:
# If a is equivalent to the result of object.some_value
if a == object.some_value
# ...
end
这是比较 ==
。
捕获形式经常用于各种情况,有时是字面上的 case
,例如您捕获笨拙 and/or 缓慢代码块的结果的地方:
case (name = professor.name.to_s.split(/\s+/).last)
when "O'Reilly", "Berners-Lee"
puts "Prof. %s is invited to the party." % name
else
puts "Prof. %s is not invited to the party."
end
其中 =
是有意分配的,因此您可以从那时起参考 name
而不必重新计算该块。