Ruby case statement
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
Previous:
Ruby If Else Unless Statement
Next:
Ruby Loops Statement
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/ruby/ruby-case-statement.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics