Switch in Ruby

Here’s the translated code and explanation in Ruby:

Switch statements express conditionals across many branches.

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.

today = Time.now.wday
case today
when 6, 0
  puts "It's the weekend"
else
  puts "It's a weekday"
end

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

now = Time.now
case
when now.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 variable. In this example, the variable t will have the type corresponding to its clause.

def what_am_i(i)
  case i
  when TrueClass
    puts "I'm a bool"
  when Integer
    puts "I'm an int"
  else
    puts "Don't know type #{i.class}"
  end
end

what_am_i(true)
what_am_i(1)
what_am_i("hey")

When executed, the XML snippet would generate the following output:

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