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

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

Determine case equality

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

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: www.rubycademy.com