Conditionals

A conditional runs a piece of code only when some expression is truthy. Ruby’s main tools for that are if (with its friends else and elsif) and case.

if

An abstract if-condition looks like this:

if expression
  program
end

The program between the expression and end runs if the result of the expression is not false and not nil.

You can also write then after the expression:

if expression then
  program
end

A concrete example:

a = 10

if a == 10
  puts 'a is 10'
end
== compares two values. Do not mix it up with the single =, which assigns.

You can try expressions out on their own in irb:

$ irb
>> a = 10
=> 10
>> a == 10
=> true
>> exit
$

Shorthand

A frequently used one-line form of if:

a = 10

# long version
#
if a == 10
  puts 'a is 10'
end

# short version
#
puts 'a is 10' if a == 10

else

Nothing surprising here, but for completeness:

a = 10

if a == 10
  puts 'a is 10'
else
  puts 'a is not 10'
end

elsif

elsif lets you check additional conditions after the first:

a = 10

if a == 10
  puts 'a is 10'
elsif a == 20
  puts 'a is 20'
end

case / when

A long chain of if / elsif / elsif works, but gets hard to read. case / when expresses the same idea more cleanly when you are comparing one value against many possibilities.

traffic-light.rb
light = 'yellow'

case light
when 'red'
  puts 'stop'
when 'yellow'
  puts 'slow down'
when 'green'
  puts 'go'
else
  puts 'unknown color'
end
$ ruby traffic-light.rb
slow down
$

case returns a value, so you can assign its result directly:

$ irb
>> light = 'green'
=> "green"
>> action = case light
?>            when 'red'    then 'stop'
?>            when 'yellow' then 'slow down'
?>            when 'green'  then 'go'
?>          end
=> "go"
>> action
=> "go"
>> exit

when is more powerful than plain equality. It also understands ranges:

grade.rb
score = 72

grade = case score
        when 0..59   then 'F'
        when 60..69  then 'D'
        when 70..79  then 'C'
        when 80..89  then 'B'
        when 90..100 then 'A'
        end

puts grade
$ ruby grade.rb
C
$