Write a Switch Statement in Ruby

Similar to how the if
statement works, the switch
statement allows us to control the execution of a code based on some specific condition. This tutorial will look at how the switch
statement is used in Ruby.
Below is the syntax for a switch
statement in Ruby.
case argument
when condition
# do something
else
# do something else if nothing else meets the condition
end
We will be looking at some common basic ways of using it and then some somewhat complex examples that are not so common.
Example Codes:
def continent_identifier(country)
case country
when "Nigeria"
puts "Africa"
when "Netherlands"
puts "Europe"
when "India"
puts "Asia"
else
puts "I don't know"
end
end
continent_identifier("India")
continent_identifier("Netherlands")
continent_identifier("Germany")
Output:
Asia
Europe
I don't know
Above is a basic example of a method that uses a switch
statement to identify a country’s continent. Looking at the above example, the following are worth noting.
- Unlike the
switch
statement in most other programming languages, Ruby’sswitch
statement does not requirebreak
at the end of eachwhen
. - Ruby’s
switch
statement allows us to specify multiple values for eachwhen
so we can return a result if our variable matches any of the values. An example is shown below.
Example Codes:
def continent_identifier(country)
case country
when "Nigeria"
puts "Africa"
when "Netherlands", "Germany"
puts "Europe"
when "India"
puts "Asia"
else
puts "I don't know"
end
end
continent_identifier("India")
continent_identifier("Netherlands")
continent_identifier("Germany")
Output:
Asia
Europe
Europe
Ruby’s switch
statement under the hood uses ===
operator to do the comparison between the case
variable and the values supplied, i.e value === argument
. As a result, Ruby switch
allows us to make more clever comparisons.
Match Ranges
in Ruby switch
In this example, we check if the supplied case
variable is included in any of the Ranges specified.
Example Codes:
def check_number(n)
case n
when 1..5
puts "Falls between 1 & 5"
when 6..10
puts "Falls between 6 & 10"
end
end
check_number(3)
check_number(7)
Output:
Falls between 1 & 5
Falls between 6 & 10
Match Regex
in Ruby switch
We can also match regular expressions against the case
variable, and that’s shown in the example below.
Example Codes:
def month_indentifier(month)
case month
when /ber$/
puts "ends with 'ber'"
when /ary$/
puts "ends with 'ary'"
end
end
month_indentifier("February")
month_indentifier("November")
Output:
ends with 'ary'
ends with 'ber'
Match Proc
in Ruby switch
A Ruby Proc
encapsulates a block of code that can be stored in a variable or passed around. You can check here for more explanation about Ruby Proc
. The following example shows how can use a Ruby Proc
in a switch
statement.
Example Codes:
def check_number(number)
case number
when -> (n) { n.even? }
puts "It's even"
when -> (n) { n.odd? }
puts "It's odd"
end
end
check_number(3)
check_number(6)
Output:
It's odd
It's even