简体   繁体   English

无|| 假和假|| 在红宝石中没有

[英]nil || false and false || nil in ruby

nil || false nil || false returns false and false || nil nil || false返回falsefalse || nil false || nil returns nil . false || nil返回nil Does anyone have an explanation for this? 有没有人对此有解释?

In Ruby, everything is an expression, and an expression will return the last value evaluated within it. 在Ruby中,一切都是表达式,表达式将返回在其中计算的最后一个值。

For both of your examples, the left side of the || 对于您的两个示例, ||的左侧 expression evaluates to a falsy value, so Ruby then evaluates the right side, and returns it. 表达式计算为一个假值,因此Ruby然后评估右侧,并返回它。

As the others pointed out, || 正如其他人指出的那样, || first evaluates the expression on the left. 首先评估左侧的表达式。 If it is "true" (anything except false or nil ), it returns that. 如果它是“true”(除了falsenil之外的任何东西),它将返回该值。 Otherwise, it evaluates the expression on the right, and returns it (no matter what it is). 否则,它会评估右侧的表达式,并返回它(无论它是什么)。

This makes || 这使得|| useful for a lot more than just boolean tests. 比布尔测试更有用。 For example, I just used it the other day when writing some code for the chronic gem: 例如,我在前几天为chronic宝石编写代码时使用它:

@now = options[:now] || Chronic.time_class.now

That means: "if the options hash includes a :now value, store that in @now . Otherwise, fall back on Chronic.time_class.now as a default". 这意味着:“如果options哈希包含:now值, @now存储在@now 。否则,将Chronic.time_class.now作为默认值返回Chronic.time_class.now ”。 I'm sure you can think of lots of possible applications in your own programs. 我相信你可以在你自己的程序中想到很多可能的应用程序。

&& is analogous: it first evaluates the expression on the left, and if it evaluates to false or nil , it returns that. &&是类似的:它首先计算左边的表达式,如果它的计算结果为falsenil ,则返回它。 Otherwise, it evaluates the expression on the right, and returns it (no matter what it is). 否则,它会评估右侧的表达式,并返回它(无论它是什么)。

This means && is also useful for a lot more than just boolean tests. 这意味着&& 也是不仅仅是布尔测试多了不少有用的。 You can use it to squeeze two lines of code into one. 您可以使用它将两行代码压缩成一行。 For example: 例如:

do_something && do_something_else

(That only works if you know that the return value of do_something will never be false or nil !) (只有当你知道do_something的返回值永远不会为falsenil时才有效!)

You can also use && to squeeze a "guard" expression on the same line as what it is "guarding": 您还可以使用&&在与“守卫”相同的行上挤压“保护”表达式:

message && send_message(message)

Which could replace: 哪个可以取代:

unless message.nil?
  send_message(message)
end

|| returns the result of the last expression evaluated. 返回最后一个表达式的结果。 If it evaluates the LHS and finds a true value, you get the LHS; 如果它评估LHS并找到true值,则得到LHS; otherwise, you get the RHS (no matter what that RHS might be). 否则,你得到RHS(无论RHS是什么)。

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

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