Rubyif语句多个条件不相等

Ruby if statement multiple conditions not equal

我不明白为什么多个不等于的 if 语句条件不起作用。在irb

2.3.0 :009 > H = Hash["a" => 100, "b" => 200, "c" => 1000, "d" => 2000]
 => {"a"=>100, "b"=>200, "c"=>1000, "d"=>2000}
2.3.0 :011 > H.each do |key, v|
2.3.0 :012 >     if (key != "a") || (key != "b")
2.3.0 :013?>     puts key
2.3.0 :014?>     end
2.3.0 :015?>   end
a
b
c
d
 => {"a"=>100, "b"=>200, "c"=>1000, "d"=>2000} 
2.3.0 :016 > H.each do |key, v|
2.3.0 :017 >     if key != "a" || key != "b"
2.3.0 :018?>     puts key
2.3.0 :019?>     end
2.3.0 :020?>   end
a
b
c
d
 => {"a"=>100, "b"=>200, "c"=>1000, "d"=>2000} 
2.3.0 :021 > H.each do |key, v|
2.3.0 :022 >     if !(key == "a") || !(key == "b")
2.3.0 :023?>     puts key
2.3.0 :024?>     end
2.3.0 :025?>   end
a
b
c
d
 => {"a"=>100, "b"=>200, "c"=>1000, "d"=>2000} 

但这行得通:

2.3.0 :026 > H.each do |key, v|
2.3.0 :027 >     if (key == "a") || (key == "b")
2.3.0 :028?>     puts key
2.3.0 :029?>     end
2.3.0 :030?>   end
a
b
 => {"a"=>100, "b"=>200, "c"=>1000, "d"=>2000} 

我在这里错过了什么?

我认为你想要实现的目标可以通过-

H.each do |key, v|
  if (key != "a") && (key != "b")
    puts key
  end
end

注意 - 如果两个条件中的任何一个为真,|| 运算符将 return 为真。

希望对您有所帮助。

的倒数
if (key == "a") || (key == "b")

实际上是

if !(key == "a") && !(key == "b")

如果你说"it can be this or that",相反的是"it cannot be this and cannot be that"