Instead of using if-elsif
statements, Ruby has another statement called case
for handling multiple options. This
statement is useful when presenting users with a large menu of different
choices. The case
statement is
expressed in Example 4-11.
1
case
2
when
(
expression1
)
3
# section 1
4
when
(
expression2
)
5
# section 2
6
else
7
# section 3
8
end
After looking at a case
statement
in use, you may be wondering what would happen if multiple when
clauses evaluate to true. Case
statements are processed in order, so the
first condition that evaluates to true has its corresponding flow option
execute, skipping over all others. As noted earlier, this processing order
is identical to the cascaded if-else
statements.
We now update the movie theater example, where children, adults, and
senior citizens have differing rates to make use of the case
statement as shown in Example 4-12.
1
puts
"Enter the customer's age: "
2
# Get an integer age value from the user
3
age
=
gets
.
to_i
4
5
# Determine the cost based on age
6
case
7
when
(
age
<=
12
)
8
cost
=
9
9
when
(
age
>=
65
)
10
cost
=
12
11
else
12
cost
=
18
13
end
14
15
# Print out the final cost
16
puts
"Ticket cost: "
+
cost
.
to_s
18.118.253.198