Case. In Ruby a case-statement tests values. The statement matches the value of a variable against ranges and other values. And it yields a specified value.
Ranges, expressions. Case is an alternative syntax form to the if-statement. We use ranges, strings and numbers with cases. We can assign or return the case's result.
Number example. This is the simplest case example. In the case, we use simple number "when" statements. For example, we return 400 when the value equals 4.
Note The case statement evaluates and its result is stored in the "result" variable's memory location.
Detail We use the case as an expression in this program, one that is evaluated to return a value.
Tip In Ruby, expressions and statements are often interchangeable. This makes constructs like "case" useful in many places.
value = 5
# Use case with numbers, no ranges.
result = case value
when 4 then 400
when 5 then 500
when 6 then 600
else 0
end
# Display input and output.
puts value
puts result5
500
Range example. Here we use case in a method. The method test() returns the value from a case-statement evaluation. It returns the strings Low, Medium or High based on the parameter.
Detail We use numeric ranges in the when-statements. To specify a range, separate two numbers with two periods.
Detail Else optionally comes at the end. If no other ranges or values match, the else-statement is reached. This is a default.
# Test method.
def test(quality)
# Return a case.
return case quality
when 0..2 then "Low"
when 3..5 then "Medium"
when 6..8 then "High"
else "Invalid"
end
end
# Call test method.
print test(0), "\n"
print test(4), "\n"
print test(8), "\n"
print test(-1), "\n"Low
Medium
High
Invalid
String. A string can be used in a case. In this example, we use a string in a case expression, and then assign an integer to the result. The case evaluates to the value 2.
Also This case expression uses an else-statement. If the value of "name" is not matched, the value 3 is returned by this expression.
# The value.
name = "sam"# Assign to result of string case expression.
id = case name
when "edna" then 0
when "fred" then 1
when "sam" then 2
else 3
end
# Display result.
puts id2
When. This can have multiple values in it. Here we see a when statement that matches if the variable equals 100 or 200. This syntax form is a good choice when a range is unnecessary.
apartment = 200
case apartment
when 100, 200
# Has two possible matching values.
puts "100 or 200"
when 0
puts "Zero"
end100 or 200
Regexp. A case can use Regexp in the when statements. Here we use a regular expression to test first letters. Any regular expression can be used. And we can even capture groups.
Here The case block detects that the word "Alexandria" starts with the letter "A." The Regexp is described.
value = "alexandria"# Use case with regular expressions.
case value
when /^a/
puts "Starts with letter A"
when /^b/
puts "Starts with B"
endStarts with letter A^a String starts with a lowercase letter A.
^b String starts with a "b".
Regexp, captures. This example combines many constructs in Ruby. We use an iterator (each) over a string array. We then use a case-statement with regular expressions.
Tip After a Regexp matches a value in a case, its groups are stored in a special variable $1. We get the captured value there.
Tip 2 We can also directly display the value of $1 in a puts call with the code #$1. This helps us develop a simple text parser.
# An array of strings.
values = ["value 100", "string box"]
# Loop over strings.
values.each do |value|
# Use regular expression in case-statement.# ... Use capturing.
case value
when /value (\d+)/
# Access the capture from $1.
argument = $1
# Use format string to display argument.
puts "Value argument = %s" % argument
when /string (.+)/
# Directly display captured value.
puts "String argument = #$1"
end
endValue argument = 100
String argument = box
Case benchmark. In this test, case has no performance advantage. It is many times slower than an equivalent if-statement. This depends on the data being tested.
Version 1 In this version of the logic, we assign a variable to the result of a case statement.
Version 2 Here, we assign a variable using an if-statement instead of the case-statement.
Result To boost performance, it is sometimes helpful to replace cases with if-statements.
count = 100000
n1 = Time.now.usec
x = 0
v = 5
# Version 1: assign a variable with a case-statement.
count.times do
x = case v
when 0..1 then 1
when 2..3 then 2
when 4..6 then 3
else 0
end
end
puts x
n2 = Time.now.usec
# Version 2: assign a variable with an if-statement.
count.times do
if v >= 0 && v <= 1
x = 1
elsif v >= 2 && v <= 3
x = 2
elsif v >= 4 && v <= 6
x = 3
else
x = 0
end
end
puts x
n3 = Time.now.usec
# Times.
puts ((n2 - n1) / 1000)
puts ((n3 - n2) / 1000)3
3
92 ms, case-statement
15 ms, if-elsif-else statements
A summary. Case is a selection statement. It is similar, conceptually, to switch statements and to select-case statements in other languages.
Case has advantages. Its syntax is clear and easy to read. It also has limitations—it may evaluate slower. We used a case-statement in a method.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 22, 2022 (edit link).