Fork me on GitHub

Demystifying Ruby’s case-when Statement

Today I was writing some code to check the type of a method parameter. I opted to use a case statement for better clarity. To my surprise I was able to simply pass the name of the class. So this got me thinking about the internals and how case-when actually works.

The case-when statement is using the === method to perform the match in the when clause of the statement.

For example, following two pieces of code are equivalent:

case 1 + 1
when 2 then puts "win"
end
if 2 === 1 + 1
  puts "win"
end

Take note of the comparison, the when clause is compared to the case clause. I thought it would be the other way around, but this makes sense.

So to create your own classes that match this condition then you would have to simply implement the === method:

class AlwaysMatches
  def self.===(value)
    true
  end
end

case :something_crazy
when /\w+_sane$/ then "this won't match"
when String then "this won't match either"
when AlwaysMatches then "Game...Set..."

# => "Game...Set..."

This class will always return true when compared in a case-when but if compared in an if statement with an equality operator will return false unless compared with itself.

The potential usage I see for this is if you have written a class that can compare with Ruby’s primitive types.

Comments

Post New Comment »

Nobody has commented on this yet.