Conditionals are an important part of the logic in any programming language. Here are the conditionals I've learned about relating to Ruby
if/elsif/else
The if
conditionals are probably some of the most common conditionals in programming, and of course Ruby utilizes them as well.
x = [0, 1, 2].sample
if x == 0
puts "X is zero!
elsif x == 2
puts "X is two!"
else
puts "X is one!"
end
As you can see, it is pretty straight forward. The code under the if
statement runs if the condition is true; if it is not true then it will attempt to run elsif
(as many as there are, in order), before finally running else
unless
unless
is a statement that is not seen in many other programming language. Logically, it is the same as if not
x = [0, 1, 2].sample
# both of these conditional statements operate the same:
unless x == 2:
puts "X is not 2"
else
puts "X is 2"
end
if x != 2:
puts "X is not 2"
else
puts "X is 2"
end
Things to keep of note: elsif
does not work with unless
, and there is also not any form of elsunless
either, so you cannot build logic statements with as many branches with an unless
statement.
Also, else
statements can occasionally seem odd to read with unless
Whether or not one uses if not
or unless
is largely a matter of personal preference, but the limitations and readability concerns above may guide a developer to choosing one over the other.
case when
case
statements are similar to switch
statements in other languages. These are conditionals that support multiple paths and various different types of input, and utilize an implicit ===
operator
x = [1, "2", 3, "4", 5, "6", 7, :rabbit].sample
case x
when 1 # 1 === x
puts "X is 1"
when "2" # "2" === x
puts "X is a string of '2'"
when 5...9 # 5...9 === x
puts "X is an integer in the range of 5 and 9"
when "5"..."9" # "5"..."9" === x
puts "X is a string in the range of '5' and '9'"
when Integer # Integer === x
puts "X is an integer not accounted for"
when String # String === X
puts "X is a string not accounted for"
when Symbol # Symbol === x
puts "X is a symbol"
end
Notice two things above.
First, in the comments, the placement of elements around the ===
operator. The order is important, the item on the left will be compared to the item on the right. String === x
is not the same as x === String
Second, notice how the ===
operator allows us to compare items more broadly, instead of having to call x.class. I will make a future post on the ===
operator on a later date, but, for now, it is worth it to mention that it allows very powerful comparisons.
I believe that case
statements are very important tools for developers to use when dealing with more complex logic blocks.
Top comments (1)
Very cool article!