This was the tip of the week in the March 18, 2021 Ruby Weekly Newsletter.


Have you ever wondered what is happening behind the scenes of a case statement in Ruby? We can write cases that look like this:

case input
when "exact match"
  "Found an exact match"
when /regex match/
  "Found a regex match"
when String
  "Input is a string"
when (1...10)
  "Input falls within this range"
end

Although this example doesn’t actually do anything useful, it does illustrate something interesting: Ruby’s case statements allow for a whole host of different types in their when clauses. In this example alone, we have a String, Regexp, Class and a Range. This is all because case statements in Ruby compare using ===.

Well, this begs the question, what exactly is a === comparison? === is most straightforward when thought of as a membership comparison. It is checking if the argument on the right of the === is a member of the argument on the left.

Here are some concrete examples based on the above:

# "exact match" is a member of "exact match"
"exact match" === "exact match"
=> true

# "string which regex matches" is a member of the
# set of matches described by /regex match/
/regex match/ === "string which regex matches"
=> true

# "another string" is a member of the String class
String === "another string"
=> true

# 1 is a member of the range (1...10)
(1...10) === 1
=> true

Now we more deeply understand what case statements are using. To read more details on the === in any specific class, take a look at the docs for that class. For instance, the === docs for String are here.