If Else in Ruby
Branching with if
and else
in Ruby is straight-forward.
Here’s a basic example:
You can have an if
statement without an else
:
Logical operators like &&
and ||
are often useful in conditions:
In Ruby, you can use a single-line conditional statement for simple checks:
Ruby also provides unless
as an alternative to if
for negative conditions:
For more complex conditions, you can use elsif
(note the spelling):
Note 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 also provides the ternary operator for simple conditional expressions:
This concise syntax is useful for simple conditions where you want to assign a value based on a condition.