Ruby Case statement Behind The Scene

Tech - RubyCademy
RubyCademy
Published in
1 min readMar 1, 2018

Syntax

A case statement consists of an optional condition followed by zero or more when conditions. It returns the value of the first truthy when statement. Otherwise nil.

str = case "match"
when "match" then "I match !"
end
# => str = "I match !"str = case "lolcat"
when "not match" then "lolcat"
end
# => str = nil

Determine case equality

Case equality is determined by the === (threequal) operator. The left operand is always the statement of the whenclause.

case "lolcat"
when String then "I'm a String"
when Fixnum then "I'm a Fixnum"
when Range then "I'm a Range"
end

Equivalent to:

if String === "lolcat"
"I'm a String"
elsif Fixnum === "lolcat"
"I'm a Fixnum"
elsif Range === "lolcat"
"I'm a Range"
end

Multiple statements

The when clause accepts multiple statements.

case "lolcat"
when String, "I'm a string" then true
end

Equivalent to:

if String === "lolcat" or "I'm a string" === "lolcat"
true
end

Each comparison is separated by an or operator.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--