If Else in Ruby
Branching with if and else in Ruby is straight-forward.
Here’s a basic example:
if 7 % 2 == 0
puts "7 is even"
else
puts "7 is odd"
endYou can have an if statement without an else:
if 8 % 4 == 0
puts "8 is divisible by 4"
endLogical operators like && and || are often useful in conditions:
if 8 % 2 == 0 || 7 % 2 == 0
puts "either 8 or 7 are even"
endIn Ruby, you can use a single-line conditional statement for simple checks:
puts "8 is even" if 8 % 2 == 0Ruby also provides unless as an alternative to if for negative conditions:
unless 7 % 2 == 0
puts "7 is odd"
endFor more complex conditions, you can use elsif (note the spelling):
num = 9
if num < 0
puts "#{num} is negative"
elsif num < 10
puts "#{num} has 1 digit"
else
puts "#{num} has multiple digits"
endNote that in Ruby, you don’t need parentheses around conditions, but the end keyword is required to close the block.
To run this Ruby script, save it as if_else.rb and execute it:
$ ruby if_else.rb
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digitRuby also provides the ternary operator for simple conditional expressions:
result = 7 % 2 == 0 ? "7 is even" : "7 is odd"
puts resultThis concise syntax is useful for simple conditions where you want to assign a value based on a condition.