Skip to content

Ruby IF...ELSE

Ruby Conditional Logic: if, else, case, unless

Section titled “Ruby Conditional Logic: if, else, case, unless”

Conditional structures allow your program to make decisions and execute different blocks of code based on whether certain conditions are true or false. Ruby provides several ways to express conditional logic.

In Ruby, only two values are considered “falsey”:

  • false (the boolean false value)
  • nil (representing no value)

Everything else, including 0, empty strings "", and empty arrays [], is considered “truthy”. This is a key concept for understanding conditional statements.

This is the standard way to execute code conditionally.

Syntax:

if condition1 [then]
# code to execute if condition1 is true
elsif condition2 [then]
# code to execute if condition1 is false and condition2 is true
else
# code to execute if all preceding conditions are false
end

The then keyword is optional, especially when the code block starts on a new line. Ruby uses elsif (not else if or elif).

Example:

#!/usr/bin/ruby
score = 75
if score >= 90
puts "Grade: A"
elsif score >= 80
puts "Grade: B"
elsif score >= 70
puts "Grade: C"
elsif score >= 60
puts "Grade: D"
else
puts "Grade: F"
end
# Example demonstrating truthiness
an_empty_string = ""
if an_empty_string
puts "An empty string is truthy in Ruby!"
end

Output:

Grade: C
An empty string is truthy in Ruby!

For single-line conditional execution, you can place if at the end of a statement.

Syntax:

statement if condition

Example:

#!/usr/bin/ruby
logged_in = true
puts "Welcome back!" if logged_in
temperature = 30
puts "It's hot!" if temperature > 28

Output:

Welcome back!
It's hot!

Executes code if a condition is false. It’s the opposite of if.

Syntax:

unless condition [then]
# code to execute if condition is false
else
# code to execute if condition is true (optional)
end

Example:

#!/usr/bin/ruby
is_raining = false
unless is_raining
puts "Let's go for a walk!"
else
puts "Better stay indoors."
end

Output:

Let's go for a walk!

Similar to the if modifier, for single-line conditional execution when the condition is false.

Syntax:

statement unless condition

Example:

#!/usr/bin/ruby
error_occurred = false
puts "All systems nominal." unless error_occurred

Output:

All systems nominal.

The case statement is useful for comparing a variable against multiple values or conditions. It uses the === (case equality or triple equals) operator for comparisons, which is more versatile than ==.

Syntax:

case expression
when value1 [, value2,...] [then]
# code for value1 or value2
when value3 [then]
# code for value3
else
# code if no when clause matches (optional)
end

The expression after case is optional. If omitted, when clauses evaluate their conditions as boolean expressions.

Example with case and different when conditions:

#!/usr/bin/ruby
def assess_value(value)
case value
when 0..10
puts "#{value} is a small number (0-10)."
when String
puts "'#{value}' is a String."
when /^[A-Z]/ # Regex: starts with an uppercase letter
puts "'#{value}' seems to be a capitalized identifier."
when :active, :pending # Multiple specific symbols
puts "Status is #{value}."
else
puts "#{value.inspect} is something else."
end
end
assess_value(5)
assess_value("hello")
assess_value("ErrorCode") # Matches regex, but String matches first if not reordered
assess_value(:pending)
assess_value([1, 2, 3])
puts "--- Case without an expression ---"
def check_permissions(user_role)
case
when user_role == :admin
puts "Full access granted."
when user_role == :editor
puts "Can create and edit content."
else
puts "Read-only access."
end
end
check_permissions(:admin)

Output:

5 is a small number (0-10).
'hello' is a String.
'ErrorCode' is a String.
Status is pending.
[1, 2, 3] is something else.
--- Case without an expression ---
Full access granted.

The === operator is powerful. For example, (0..10) === 5 is true, String === "hello" is true, and /pattern/ === "string" checks if the string matches the regex.

For simple if/else logic that assigns a value to a variable, the ternary operator provides a concise alternative.

Syntax:

result = condition ? value_if_true : value_if_false

Example:

#!/usr/bin/ruby
age = 20
status = age >= 18 ? "Adult" : "Minor"
puts "Status: #{status}" # Output: Status: Adult

Practical Applications:

Conditional logic is the backbone of program flow. It’s used for: validating user input, controlling access based on permissions, handling different states of an application, implementing business rules, customizing output, and much more. Choosing between if/elsif/else, case, or modifiers depends on the complexity and readability desired.