Ads by ProfitSence
Close

Switch statement in Ruby Code Example

Last Updated on Wednesday 5th Oct 2022

Ruby doesn't have a switch statement, unlike other programming languages.

  • Instead, there's the case expression, which is much versatile and powerful than a switch.

A case expression in ruby consists of three parts

  • case: The variable we are going to match.
  • when: A condition to match.
  • else: The default choice.

Example 1

			
					number = 0

case number
when 0
puts "Less than 5"
when 10
puts "Equals to 10"
when 20
puts "More than 10"
else
  puts "Oops Invalid."
end

# Less than 5

			
	
  • You can assign its value to a variable.

Example 2

			
					number = 10

result =
  case number
when 0
  "Equals to 0"
when 10
  "Equals to 10"
when 20
  "Equals to 20"
else
  "No Case here for that number."
end

puts result

# Equals to 10

			
	

Example 3

			
					val = 4

case val
when 1, 4, 9
puts "It's a square."
when 2, 3, 5, 6, 7, 8
puts "Not a square."
end

# It's a square