w3resource logo


Ruby tutorials

Ruby case statement

Secondary Nav

Case Statement

A case expression is an alternate of if-elsif-else expression.

Syntax:

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

Here is an example to determine the relationship of a number :

x = 1
case 
when x < 0 then puts "#{x} is less than 0"    
when x == 0 then puts "#{x} equals to 0"   
when x > 0 then puts "#{x} is greater than 0" 
end

Output :

1 is greater than 0

Here is an alternate syntax to determine the relationship of a number

x = 22
case x
  when 0..14 then puts "#{x} is less than 15"    
  when 15 then puts "#{x} equals 15" 
  when 15..20 then puts "#{x} is greater than 15" 
  else puts "Not in the range, value #{x} " 
 end

Output :

Not in the range, value 22

Example : Compare a String against a pattern using case :

s = "A1002"
case s
when /^A/
  puts "The string starts with A"
else
  puts "The starting character of the string is not A"
end

Output:

The string starts with A



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables