rubydemorgans-law

Ruby if statement multiple conditions not equal


I can't figure out why multiple if statement conditionals with not equals doesn't work. In 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} 

But this works:

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} 

What am I missing here?


Solution

  • I think what you are trying to achieve, can be done by-

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

    Note - || operator will return true if any of the two conditions is true.

    Hope that helps.