1

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.

Fred
  • 13
  • 3
  • What is the error? It might actually be caused by the content of the code block, not the `unless` line – max pleaner Aug 07 '20 at 16:27
  • The error is indeed a line in the code block. When I use || the code block appears to be ignored entirely therefore avoiding the error. If I don't use || or use a &&, the error in the code block is raised. Essentially, the second part after the || (which is evaluating to true) makes it skip the block. I just don't understand why it's skipping. – Fred Aug 07 '20 at 16:42

1 Answers1

5

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

code_aks
  • 1,972
  • 1
  • 12
  • 28
  • 2
    This is great! So the error is raised when && is used as it evaluates to false. But error is not raised when || is used as it evaluates to true and therefore does not run the code block. Thanks! – Fred Aug 07 '20 at 17:09