Search code examples
rubyblock

Ruby blocks - unless and if comparison


I have a doubt regarding unless and if blocks in ruby language. Please excuse me if I'm that stupid to ask this question.

Lets assume we have two boolean variables a = true and b = true.

condition: I want to check whether both of them are true. Using if statement we can check that as given below.

if a == true && b == true
  print "Hai"
end

doubt: instead of the above statement, can I use the one given below?

unless a == false && b == false
  print "Hai"
end

Will both the blocks given above give the same result?


Solution

  • Instead of

    if a == true && b == true
      print "Hai"
    end
    

    you can write

    if a && b
      print "Hai"
    end
    

    This is the same as

    unless !(a && b)
      print "Hai"
    end
    

    Which is (using De Morgan's laws) the same as

    unless !a || !b
      print "Hai"
    end