Ruby Language Reference

case statement

Simple comparison of variable x with an integer.

x = 1
case x
when 1
  p "It's 1"
when 2
  p "It's 2"
when 3
  p "It's 3"
else
  "The value is #{x} - This is not handled"
end

You can have a list of numbers in the expression for when clause:

x = 4
case x
when 1,2,3,4
  p "You entered 1, 2, 3 or 4"
when 10
  p "You entered 10"
else
  puts "You entered #{x}"
end

A case statement can be used with Ranges.

marks = 89
case marks
when 79..90
  p "You got a B"
when 100
  "You got an A"
end

A case statement can be used with a Regexp:

case "funny"
when /nn/
  puts "word contains nn"
end

A case statement can be used with a Proc or lambda.

x = 3
case x
when -> (n) { n.odd? }
  p "It's an odd number"
else
  p "The value is #{x}"
end

The === operator is used to compare the expression in the case clause with the expression in the when clause. If they match the code of the when clause is executed. If no when clauses match, case executes the code of the else clause.

We are able to use Procs in the when clause because they implement the === operator. We can create our own match classes by implementing the === method.

class BlankName
  def self.===(object)
    !object or "" == object
  end
end

name = ""
case name
when BlankName
  p "The name is blank"
else
  p "The name is #{name}"
end

This prints: The name is blank. The case statement has a value, you can assign it to a variable:

speed = case 35
when 25..35
  'residential'
when 65..75
  'highway'
else
  ''
end

p speed

This will print residential.


Sharing is Caring