Case with Classes & Regex
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 38 of 56.
You've used case with ranges. The same statement also matches against classes and regular expressions: both via the === operator that when calls under the hood.
Match by class to branch on what kind of value you got:
def describe(value)
case value
when Integer then "a whole number"
when Float then "a decimal"
when String then "some text"
else "something else"
end
end
puts describe(42) # a whole number
puts describe(3.14) # a decimal
puts describe("hi") # some textMatch against a regex to branch on a string's shape, a phone number, an email, a date:
def kind_of(text)
case text
when /^\d+$/ then "all digits"
when /@/ then "looks like an email"
when /^[A-Z]/ then "starts with a capital"
else "other"
end
endThis is far cleaner than a chain of is_a? or match? calls in if/elsif.
Challenge
EasyRead a single line of input. Use a case statement to print one of these labels based on what the input looks like:
- All digits,
number - Contains
@:email - Starts with a capital letter,
name - Anything else,
unknown
Check the rules in the order listed (so 123 is number, not unknown; kevin@coddy.tech is email; Alice is name).
For input kevin@coddy.tech, the output is email.
Cheat sheet
Ruby's case/when matches against classes and regular expressions using === under the hood.
Match by class:
case value
when Integer then "a whole number"
when Float then "a decimal"
when String then "some text"
else "something else"
endMatch by regex:
case text
when /^\d+$/ then "all digits"
when /@/ then "looks like an email"
when /^[A-Z]/ then "starts with a capital"
else "other"
endTry it yourself
input = gets.chomp
# TODO: case input ... when /^\d+$/, /@/, /^[A-Z]/ ... else ... end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier