Ruby provides mechanisms for controlling the control-flow of a program. They consist of the if-statement families, if
, elsif
, else
, and unless
. Along with case/when
.
“The basic idea of the case/when structure is that you take an object and cascade through a series of tests for a match, taking action based on the test that succeeds.”. Black, D. A., & Leo, J. (2019). The well-grounded Rubyist. Manning.
A typical case statement looks like this
tool = "google" case tool when "google" puts "tool is google" when "basecamp" puts "tool is basecamp" else puts "unknown tool" end
Every ruby object has a case equality method, called ===
, triple equal sign, sometimes called as case subsumption or threequal operator
instead of doing when tool.=== "google"
. The when "google"
keyword provides a syntactical sugar over the previous approach.
The threeequal operator is defined everywhere on every built-in class. You can also implement in classes that you define.
Let's define a Car
class.
class Car attr_accessor :brand, :type def initialize(brand, type) self.brand = brand self.type = type end def ===(other_car) self.brand == other_car.brand end end
Now, we can use them along with case/when.
ford = Car.new "Ford", "F-150" jeep = Car.new "Jeep", "Wrangler" tesla_model_x = Car.new "Tesla", "Model-X" tesla_model_y = Car.new "Tesla", "Model-Y" case tesla_model_x when ford puts "It's a ford" when jeep puts "It's a Jeep" when tesla_model_y puts "Both are Tesla made" else puts "unknown manufacturer" end
running this through a ruby session, we get the following
Both are Tesla made => nil
Underneath, the ruby interpreter makes a call to the ===
method on the object, which we defined inside the Car
class
def ===(other_car) self.brand == other_car.brand end
With tripleequal sign operator or case subsumption operator you can allow your classes to work elegently with Ruby's case/when control-flow operators.
Thanks for reading, and Happy Coding.
Top comments (0)