Skip to content

Conditional Statements

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

The unless statement is similar to the if statement and simply negates the if logic, but does not (yet?) have an elsunless capability.

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.

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.

Ternary Operator

Ruby implements a Ternary Operator similar to many other programming languages.

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.

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.

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.