为什么在 select 方法中使用 OR 运算符而不是 AND 运算符?

Why is the OR operator used instead of AND operator in the select method?

给定家庭成员的散列,以键作为标题,以名称数组作为值,使用 Ruby 的 built-in select 方法仅收集直系亲属成员的名字到一个新数组中。

# Given

family = {  uncles: ["bob", "joe", "steve"],
            sisters: ["jane", "jill", "beth"],
            brothers: ["frank","rob","david"],
            aunts: ["mary","sally","susan"]
          }

解决方法是:

immediate_family = family.select do |k, v|
  k == :sisters || k == :brothers
end

arr = immediate_family.values.flatten

p arr

为什么在 select 方法中使用 || 运算符而不是 && 运算符?当我 运行 它与 && 时,select 方法 returns 一个空数组。

想一想。你的k是一个符号,一个符号不能同时是:sisters:brothers吧?因此,使用 && 块永远不会为真。

但在另一种情况下 && 可以完成这项工作。假设您想过滤掉 20 岁以上和 60 岁以下的人。

people.select { |person| person.age > 20 && person.age < 60 }

在大多数编程语言中,||&& 运算符分别表示 orand

表达式:

family.select do |k, v|
  k == :sisters || k == :brothers
end

将转换为 "select all elements of the familiy hash where the key is :sisters or :brothers"。正如@Ursus 指出的那样,在这种情况下,k 同时等于 :brother:sister 是没有意义的。

&&||是逻辑运算符:

  • a && b 是真实的,如果 ab 都是真实的
  • 如果 a 为真或 b 为真(或两者),则
  • a || b 为真

truthy(在 Ruby 中)表示除 nilfalse.

之外的所有内容

让我们看看会发生什么,如果 ak == :sisters 并且 bk == :brothers:

k           a       b       a && b   a || b
:uncles     false   false   false    false
:sisters    true    false   false    true
:brothers   false   true    false    true
:aunts      false   false   false    false

对于给定的值,a && b 将始终 return false,而 a || b 将 return true 如果 k:sisters 或者如果 k:brothers。这就是你想要的。