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 xwhen x_1#code to executewhen x_n#code to execute.else#code to executeend
Code
years = 2case yearswhen 0,1puts "You are eligible to be a project coordinator"when 2,3,4,5,6puts "You are eligible to be a project manager"elseputs "You are ineligible"end
In the code snippet above:
Line 3: If
yearsequals0or1,"You are eligible to be a project coordinator"is printed.Line 5: If
yearsis between2and6(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 = 2case yearswhen 0..1puts "You are eligible to be a project coordinator"when 2..6puts "You are eligible to be a project manager"elseputs "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 xwhen /World$/puts "#{x} ends with World"elseputs "#{x} does not end with World"end
In the code snippet above:
Line 3: If
xends withWorld, then the code inside thewhenclause is printed.Line 5: Otherwise, the code inside
elseis 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 = 2case numberwhen is_div_by_10puts 'The number is divisible by 10'elseputs 'The number is not divisible by 10'end
In the code snippet above:
Line 4: If the
numberis divisible by10,"The number is divisible by 10"is printed.Line 6: Otherwise, the code inside
elseis printed.
Free Resources