Introduction To Ruby
Case Statements

Most languages have an equivalent of the case statement. In Visual Basic it is called Select Case, in many of the C family languages, it is called switch. The following examples show how the case statement can be used in Ruby.

Example 1

In this example, all of the case statement is concerned with the value of a single variable, choice.

# case Example 1

print "Enter the first number: "
first = gets.chomp.to_i
print "Enter the second number: "
second = gets.chomp.to_i

# output spread over several lines
puts "
1. Add the numbers
2. Subtract the numbers

Choose Wisely
"

choice = gets.chomp.to_i

case choice
when 1 then
  answer = first + second
when 2 then
  answer = first - second
else
  answer = "Error"
end

puts "The answer is: #{answer}"

gets

Example 2

If there is no variable or expression to the right of the case statement, the when clauses can each contain the condition that needs to be evaluated.

# case Example 2

x = 5
y = -2

case
when x==5 then
  puts "x is 5"
when y<0 then
  puts "y is negative"
when x>10 && y<0 then
  puts "x is more than 10 and y is negative"
else
  puts "no conditions met"
end

gets

Notice that, when you execute this code as is, the second when is not evaluated. In Ruby, the statement ends as soon as one of the conditionals evaluates to true. The conditions do not collapse into one another as they do in some C family languages.

Example 3

You can use range objects in the when clauses to make the code easier to read.

# case Example 3

print "Enter an exam score out of 100: "
score = gets.chomp.to_i

case score
when 0..50 then
  puts "U"
when 51..65 then
  puts "C"
when 66..75 then
  puts "B"
when 76..100 then
  puts "A"
else
  puts "Error"
end

gets

Challenges

  1. Get the user to enter the number of a month. Use a case statement to display the name of the corresponding month and the number of days in that month.
  2. Write a program that accepts 3 integers. One should be a number from 1 to 7 representing the day of the week. Another should be a number corresponding to the month. The final number should be the date (1 - 31). Output the date that was entered in words. For example, 'Monday 25th September'