How to write a switch statement in Ruby

The case expression in Ruby is much like the switch statement in other languages like Golang. It consists of zero or more when clauses and can end with an optional else clause. The object in the when clause is compared with the object in the case clause with the help of the === operator.

Syntax

case x
when x_1
#code to execute
when x_n
#code to execute
.else
#code to execute
end

Code

years = 2
case years
when 0,1
puts "You are eligible to be a project coordinator"
when 2,3,4,5,6
puts "You are eligible to be a project manager"
else
puts "You are ineligible"
end

In the code snippet above:

  • Line 3: If years equals 0 or 1, "You are eligible to be a project coordinator" is printed.

  • Line 5: If years is between 2 and 6 (both inclusive), "You are eligible to be a project manager" is printed.

  • Line 7: For all other values of years, "You are ineligible" is printed.

Ranges in the case statement

The above code can be rewritten with ranges in the following manner:

years = 2
case years
when 0..1
puts "You are eligible to be a project coordinator"
when 2..6
puts "You are eligible to be a project manager"
else
puts "You are ineligible"
end

Regular expressions in the case statement

Regular expressions can also be used in case statements. Take a look at the following code:

x = "HelloWorld"
case x
when /World$/
puts "#{x} ends with World"
else
puts "#{x} does not end with World"
end

In the code snippet above:

  • Line 3: If x ends with World, then the code inside the when clause is printed.

  • Line 5: Otherwise, the code inside else is printed.

Lambdas in the case statement

Lamdas can be used in the case statement. The following code demonstrates this:

is_div_by_10 = ->(x) { x % 10 == 0 }
number = 2
case number
when is_div_by_10
puts 'The number is divisible by 10'
else
puts 'The number is not divisible by 10'
end

In the code snippet above:

  • Line 4: If the number is divisible by 10, "The number is divisible by 10" is printed.

  • Line 6: Otherwise, the code inside else is printed. 

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved