Ruby Case
case matches a value with when clauses using ===. It supports ranges, classes, regexes and lambdas, and returns a value.
Example
def kind(x)
case x
when Integer then "int"
when 1.0..2.0 then "small float"
when /^a/ then "starts with a"
when nil then "nil"
else "other"
end
end
puts kind(5), kind(1.5), kind("apple"), kind(nil)Result
int small float starts with a nil
Exercise
Fallback clause.
case x when 1 then 1 0 end
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.