Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marian13/409f69f9a4e50a9abc460eec608843c6 to your computer and use it in GitHub Desktop.
Save marian13/409f69f9a4e50a9abc460eec608843c6 to your computer and use it in GitHub Desktop.

A proof that unless condition_1 && condition_2 is the same as if !condition_1 || !condition_2.

  • Create a file.

    touch test.rb
  • Paste the following content inside of it.

def test
  conditions = [
    [true, true],
    [true, false],
    [false, true],
    [false, false],
  ]

  conditions.each do |first_condition, second_condition|
    unless_result =
      unless first_condition && second_condition
        true
      else
        false
      end

    if_result =
      if !(first_condition && second_condition)
        true
      else
        false
      end

    parsed_if_result =
      if !first_condition || !second_condition
        true
      else
        false
      end

    results = [unless_result, if_result, parsed_if_result]

    puts "| #{"unless #{first_condition} && #{second_condition}".to_s.ljust(21)} | #{unless_result.to_s.ljust(5)} |"
    puts "| #{"if !(#{first_condition} && #{second_condition})".to_s.ljust(21)} | #{if_result.to_s.ljust(5)} | "
    puts "| #{"if !#{first_condition} || !#{second_condition}".to_s.ljust(21)} | #{parsed_if_result.to_s.ljust(5)} |"
    puts

    if results.uniq.count != 1
      raise "`unless condition_1 && condition_2' is NOT the same as `if !condition_1 || !condition_2'"
    end
  end
end

test

puts "OK"
  • Run test.rb.
ruby test.rb
  • If you see no errors, then unless condition_1 && condition_2 is the same as if !condition_1 || !condition_2.
| unless true && true   | false |
| if !(true && true)    | false | 
| if !true || !true     | false |

| unless true && false  | true  |
| if !(true && false)   | true  | 
| if !true || !false    | true  |

| unless false && true  | true  |
| if !(false && true)   | true  | 
| if !false || !true    | true  |

| unless false && false | true  |
| if !(false && false)  | true  | 
| if !false || !false   | true  |

OK

Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment