Switch in Crystal

Here’s a basic switch.

i = 2
print "Write #{i} as "
case i
when 1
  puts "one"
when 2
  puts "two"
when 3
  puts "three"
end

You can use commas to separate multiple expressions in the same when statement. We use the optional else case in this example as well.

case Time.local().day_of_week
when 0, 6
  puts "It's the weekend"
else
  puts "It's a weekday"
end

case without an argument is an alternate way to express if/else logic. Here we also show how the when expressions can be non-constants.

t = Time.local
case
when t.hour < 12
  puts "It's before noon"
else
  puts "It's after noon"
end

A type case compares types instead of values. You can use this to discover the type of a value. In this example, the variable t will have the type corresponding to its clause.

def what_am_i(i)
  case i
  when Bool
    puts "I'm a bool"
  when Int32
    puts "I'm an int"
  else
    puts "Don't know type #{typeof(i)}"
  end
end

what_am_i(true)
what_am_i(1)
what_am_i("hey")
$ crystal run switch.cr
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String