Last updated on June 30th, 2024 at 03:04 pm
Every programming language needs conditional statements to control the flow of logic.
Table of Contents
If and Unless
As with just about every other language in existence, Ruby has the conditional statement if
. Knowing how much Ruby loves positive statements, it also has the conditional statements unless
which can basically be considered the negation of the if
.
The if
statement works as one would expect
if expression
expression
elsif expression
expression
else
expression
end
The unless
statement is similar to the if
statement and simply negates the if logic, but does not (yet?) have an elsunless
capability.
unless expression
expression
else
expression
end
One very interesting aspect of Ruby is that you can actually assign the if
/ unless
statement and the last value in the execution block is assigned to the variable.
new_value = if expression
expression
elsif
expression
else
expression
end
Conditional Statements
Ruby implements an interesting mechanism with conditionals. It allows you do execute an expression based upon whether or not the conditional is fulfilled.
var1 = "A string" if some_value_is_true
var2 = "A different string" unless some_value_is_false
Ternary Operator
Ruby implements a Ternary Operator similar to many other programming languages.
var = expression ? true-assignment : false-assigment
Case
Ruby also has a case
statement, that works very much as one would expect. As with the if
and unless
, the results of the case
can also be assigned.
case object
when expression
expression
else
expression
end
The case statement also has an “in” operator, which is hardly documented at all on the Internet. From what I have been able to find, it appears to check if the target value is in a collection.
a1 = [1,2,3,4,5]
a2 = [6,7,8,9,10]
case 1
in a1
puts "in a1"
in a2
puts "in a2"
end
For an interesting example of how the “in” operator works with JSON data, I suggest you have a look at a post by Brandon Weaver.