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.
case xwhen x_1#code to executewhen x_n#code to execute.else#code to executeend
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 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.
case
statementThe 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
case
statementRegular 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 x
ends with World
, then the code inside the when
clause is printed.
Line 5: Otherwise, the code inside else
is printed.
case
statementLamdas 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 number
is divisible by 10
, "The number is divisible by 10"
is printed.
Line 6: Otherwise, the code inside else
is printed.
Free Resources