typestar

case and when in Ruby

Pattern dispatch with ===: ranges, classes and regexps all match.

# case matches with ===, so ranges, classes and regexps all work
def describe(value)
  case value
  when nil then "nothing"
  when 1..10 then "small number"
  when Integer then "number #{value}"
  when /\Arb/ then "starts with rb"
  when String then "#{value.length} characters"
  else "unknown"
  end
end

puts describe(nil)
puts describe(7)
puts describe(42)
puts describe("rbenv")
puts describe("typestar")

How it works

  1. case compares with ===, so branches can be types or patterns.
  2. when 1..10 catches small numbers before Integer sees them.
  3. A regexp branch matches strings starting with rb.
  4. then keeps single-expression branches on one line.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
393
Tokens
86
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 2 of 3 in Control flow, step 8 of 29 in Language basics.

← Previous Next →