我不明白 Ruby 文档中在 if 表达式中分配值的代码



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,例如您捕获尴尬和/或慢速代码的结果:

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,而不必重新计算该块。

最新更新