Ruby Case statement Behind The Scene

Mehdi Farsi
Mar 1, 2018 · 2 min read

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.

Voilà!

May I have your attention please 🎤🎤

Feel free to subscribe here:


Thank you for taking the time to read this post :-)

Feel free to 👏 and share this Medium post if it has been useful for you.

rubycademy

E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of www.rubycademy.com — I blog about Ruby & ROR - Paris

rubycademy

E-Learning platform for Ruby and Ruby on Rails

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade