Conditional Execution
Booleans
There are three boolean values in Ruby: true
, false
& nil
.
They are all built-in Ruby objects.
false
& nil
are the only falsy
values in Ruby. All other expressions, including true
, 0
(zero) and ""
(empty string), are truthy
. This disambiguation is important especially with regards to control flow in Ruby.
puts "I will be printed!" if true # => "I will be printed!"
puts "I won't be printed!" if false # => nil
puts "I won't be printed as well!" if nil # => nil
if
if
expression controls whether a selected expression is executed or not.
if
can be used as a multi-line expression:
if should_do_something?
do_something
end
if
can also be used as a single line expression:
do_something if should_do_something?
In both cases do_something
is executed if should_do_something?
evaluates to a truthy value.
if elsif
if
expression can also be extended with an elsif
keyword. The code following the elsif
keyword is executed provided should_do_a?
evaluates to a falsy value and should_do_b?
evaluates to a truthy value.
if should_do_a?
do_a
elsif should_do_b?
do_b
end
if else
if
expression can be extended with an else
keyword. The code following the else
keyword is executed provided should_do_a?
evaluates to a falsy value.
if should_do_a?
do_a
else
do_b
end
if elsif else
if
, elsif
and else
can be combined.
if
expression can be extended with both elsif
and else
keywords. The code following the if
expression is executed provided should_do_a?
evaluates to a truthy value. The code following the elsif
keyword is executed provided should_do_a?
evaluates to a falsy value and should_do_b
evaluates to a truthy value. The code following the else
keyword is executed provided both should_do_a?
and should_do_b
evaluate to falsy values.
if should_do_a?
do_a
elsif should_do_b?
do_b
else
do_c
end
case
case
expression can be used to check for multiple conditions.
case foo
when condition_a
do_a
when condition_b
do_b
else
do_c
end
The conditions are being evaluated using ===
method where the condition is the receiver and the expression following the case
keyword is the argument. In other words when truthfulness of the condition_a
is being evaluate it sends message ===
to condition_a
with the argument of foo
.