ruby-on-railsrubyconditional-statementsdemorgans-lawunless

Ruby unless conditional with || operator


I am confused about how the Ruby unless conditional works with the || operator.

So what I've got essentially:

<% unless @instance_variable.method || local_variable.another_method %>
  code block
<% end %

At the moment, the first part is evaluating to false and the second part to true. And I do not get an error raised, it does what I want. However, if I just write:

<% unless @instance_variable.method %>
  code block
<% end %>

I get an error thrown and I get an error when I write:

<% unless @instance_variable.method && local_variable.another_method %>
  code block
<% end %>

So my question. If the first part is evaluating to false, will it cut short and go through the code block, and not looking at the other side? If so, why does leaving the second part out throw an error? And hows does it all work?

Apologies if you need the code, I feel like this is a logic/algebra solution.


Solution

  • Unless is the exact opposite of If. It’s a negated If.

    Unless will work when the condition is false

    2.3.4 :010 > unless false || false
    2.3.4 :011?>   puts "unless block"
    2.3.4 :012?>   end
    unless block
    => nil 
    

    So by this or condition || result is false when both sides are false

    2.3.4 :019 > false || false
     => false
    

    else the result is always true

    below code will not execute the puts statement because the condition gives true

    2.3.4 :022 >   unless false || true 
    2.3.4 :023?>   puts "unless block"
    2.3.4 :024?>   end
     => nil 
    
    2.3.4 :019 > false || true
         => true
    

    And your && is worked because it gives false when execute below stmt and unless worked with false :-

     2.3.4 :019 > false && true
         => false 
    

    For more here is a reference https://mixandgo.com/learn/if-vs-unless-in-ruby