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.
Truthiness and Falsiness in Ruby:
Section titled “Truthiness and Falsiness in Ruby:”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.
Ruby if...elsif...else Statement:
Section titled “Ruby if...elsif...else Statement:”This is the standard way to execute code conditionally.
Syntax:
if condition1 [then] # code to execute if condition1 is trueelsif condition2 [then] # code to execute if condition1 is false and condition2 is trueelse # code to execute if all preceding conditions are falseendThe 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 truthinessan_empty_string = ""if an_empty_string puts "An empty string is truthy in Ruby!"endOutput:
Grade: CAn empty string is truthy in Ruby!Ruby if modifier (postfix if):
Section titled “Ruby if modifier (postfix if):”For single-line conditional execution, you can place if at the end of a statement.
Syntax:
statement if conditionExample:
#!/usr/bin/ruby
logged_in = trueputs "Welcome back!" if logged_in
temperature = 30puts "It's hot!" if temperature > 28Output:
Welcome back!It's hot!Ruby unless Statement:
Section titled “Ruby unless Statement:”Executes code if a condition is false. It’s the opposite of if.
Syntax:
unless condition [then] # code to execute if condition is falseelse # code to execute if condition is true (optional)endExample:
#!/usr/bin/ruby
is_raining = false
unless is_raining puts "Let's go for a walk!"else puts "Better stay indoors."endOutput:
Let's go for a walk!Ruby unless modifier (postfix unless):
Section titled “Ruby unless modifier (postfix unless):”Similar to the if modifier, for single-line conditional execution when the condition is false.
Syntax:
statement unless conditionExample:
#!/usr/bin/ruby
error_occurred = falseputs "All systems nominal." unless error_occurredOutput:
All systems nominal.Ruby case Statement:
Section titled “Ruby case Statement:”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 expressionwhen value1 [, value2,...] [then] # code for value1 or value2when value3 [then] # code for value3else # code if no when clause matches (optional)endThe 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." endend
assess_value(5)assess_value("hello")assess_value("ErrorCode") # Matches regex, but String matches first if not reorderedassess_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." endend
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.
Ternary Conditional Operator (? :):
Section titled “Ternary Conditional Operator (? :):”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_falseExample:
#!/usr/bin/ruby
age = 20status = age >= 18 ? "Adult" : "Minor"puts "Status: #{status}" # Output: Status: AdultPractical 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.