简体   繁体   English

Ruby Newbie:对布尔逻辑感到困惑

[英]Ruby Newbie: Confused About Boolean Logic

I have an array, if I find a value in it, I want to execute a block of code. 我有一个数组,如果我在其中找到一个值,我想执行一段代码。 Also, if the array is nil, I want to execute that block. 另外,如果数组为nil,我想执行该块。 So the code I tried is: 所以我尝试的代码是:

if !array.respond_to? :index || array.index(str)
  #some code

So if it's nil it's true, or if str is somewhere in the array, it's true, right? 因此,如果它为nil,则为true,或者str在数组中的某处,则为true,对吗? But if it finds the item at index 0, it doesn't enter the block. 但是,如果找到索引为0的项目,则不会进入该块。 Also, according to irb false || 0 另外,根据irb false || 0 false || 0 evalueates to 0 . false || 0等于0 WTF?? WTF? I thought that everything was true except false and nil. 我以为除假和零外,其他一切都是真的。 I guess || 我猜|| does something odd that I'm not expecting?? 有什么奇怪的事我没想到吗?

My questions are: What's going on? 我的问题是:怎么回事? What's a nice way to write a conditional that does what I want? 编写满足我条件的条件的一种好方法是什么?

if array.nil? || array.member?(s)
    # ...

false || 0 false || 0 evaluates to 0 because it's an or . false || 0等于0因为它是or False isn't truthy (obviously ;) but 0 is, so the expression is truthy. False不是真实的(很明显;),但是0是真实的,因此表达式是真实的。

Using nil? 使用nil? and include? include? with an inline if seems most idiomatic to me. 内联, if对我来说似乎最惯用。

#your code if arr.nil? || arr.include?(str)

Are you checking for a nil array or an empty one? 您要检查的是nil数组还是空数组? If you've already declared the array it won't be nil even if it's empty. 如果您已经声明了数组,即使它为空也不会为零。 I'd write it like: 我会这样写:

if array.empty? || array.include(str)

or if you really want to check for a nil array: 或者,如果您真的要检查nil数组:

if array.nil? || array.include(str)

I'd use .include rather than .index to avoid getting a 0. 我会使用.include而不是.index以避免得到0。

if array.nil?­ || array­.member?(str­)
    #code block
end

The || || operator almost reminds you of a coalesce. 操作员几乎使您想起合并。

Given a = false, b = :bacon 给定a = false,b =:bacon

return a || b #returns :bacon

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

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