Menu
Coddy logo textTech

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 text

Match 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
end

This is far cleaner than a chain of is_a? or match? calls in if/elsif.

challenge icon

Challenge

Easy

Read 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"
end

Match 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"
end

Try it yourself

input = gets.chomp

# TODO: case input ... when /^\d+$/, /@/, /^[A-Z]/ ... else ... end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow