So I am writing a Ruby program for school that changes the value of a boolean to true if a certain value is either 1 or 3, and to false if it is 0 or 2. Since I come from a Java background, I thought that this code should work: if n == 1 || n == 3
But it does not. So my question here is is it possible to use an “Or” expression thingy in If blocks in Ruby? I know that my current situation could be solved easily by just something like the following:
if n == 0
t_o_f = false
elsif n == 1
t_o_f = true
Et Cetera. But I want to know if I can use an Or in If blocks for the future.
Yes, any expression can be used in an
ifcondition, including those using the||(logical or) operator.As with Java, Ruby’s
||operator short-circuits. That is, if the left side is true, the right side is not evaluated.Idiomatic ruby uses postfix if for one-liners:
Avoid postfix if the line is long, however, and break it into multiple lines:
That’s because postfix if can get visually lost at the end of a long line.
You can have a one-liner with prefix if, but it’s not commonly seen:
or, perhaps:
This is really a multi-line if condensed into one line; the semicolons act as line breaks.
When testing for multiple conditions, it can sometimes be valuable to use
Array#include?:The value of this for only two conditions is not that great. For three or more, it reads well.