Javascript developer learning Ruby: Case Equality Operator
As a JavaScript developer learning Ruby, one of the most unexpected discoveries for me so far was the case equality operator (===)
.
In JavaScript, ===
is all about strict equality, meaning both value and type must match:
console.log(5 === '5'); // false
console.log(5 === 5); // true
But in Ruby, ===
is not even about equality check. it's a cool pattern-matching tool that makes conditional logic more elegant and expressive.
How === Works in Ruby
The ===
operator is primarily used in case statements and allows objects to define their own custom behavior.
Ranges
(1..10) === 5 # => true
(1..10) === 15 # => false
This means 5 is within the range 1..10. One of the things I dislike about if statements in JS is that you have to repeat the variable name in every condition (e.g. if num >= 1 && num <= 10
). I know, it is not the end of the world obviously, but when I see a more elegant way of doing things, I can't help but appreciate it.
Classes and Modules (Module#===): Is the object an instance of a class?
String === "hello" # => true
Integer === "hello" # => false
Custom Behavior in Classes (#=== Overriding)
I think this is the coolest part. You can override the ===
method in your own classes to define custom behavior. For example, you could use it to check if an object is valid or meets certain criteria.
class EvenNumber
def ===(num)
num.even?
end
end
case 4
when EvenNumber.new then puts "It's even!"
else puts "It's odd!"
end
Wrap
I am really liking so far how expressive and flexible Ruby is. Wrapping up with this;
JAVASCRIPT 👇
function classify(value) {
if (value >= 1 && value <= 10) {
return 'Number is between 1 and 10';
} else if (typeof value === 'string') {
return "It's a string!";
} else if (/\d+/.test(value)) {
return 'Contains a digit';
} else {
return 'Something else';
}
}
RUBY 👇
def classify(value)
case value
when 1..10 then "Number is between 1 and 10"
when String then "It's a string"
when /\d+/ then "Contains a digit"
else "Something else"
end
end
Love this elegancy 💅