The rarely used === in Ruby
===
is almost never seen in Ruby. It's nothing like the JavaScript version of the operator. It is up to the class in question as to what it means. Here are a few examples:
Regexes
/^zzz/ == 'zzzbb' # => false
/^zzz/ === 'zzzbb' # => true
Case Statements
Case statements use ===
This can be really useful for something like the following:
def tracking_service(num)
case num
when /^.Z/ then :ups
when /^Q/ then :dhl
when /^96.{20}$/ then :fedex
when /^[HK].{10}$/ then :ups
end
end
tracking_service('zZ') # => :ups
tracking_service('Qlksjdflk') # => :dhl
tracking_service('H2828282822') # => :ups
Array.grep
Arrays have a method called grep
that uses ===
["apple juice", "carrot juice", "coca-cola"].grep /juice/ # => ["apple juice", "carrot juice"]
Ranges
===
checks to see if a number is contained.
(2..4) == 3 # => false
(2..4) === 3 # => true
(2..4) === 6 # => false
Lambdas
Lambdas evaluate under ===
is_even = -> (x) { x % 2 == 0 }
is_even == 4 # => false
is_even === 4 # => true
is_even === 5 # => false
Written by dickeyxxx
Related protips
4 Responses
Credit to http://stackoverflow.com/users/23649/jtbandes for explaining some of these concepts on StackOverflow
Class objects implement === as "is_a?". Which is kind of neat for case statements, but also has a couple of gotchas:
From the (unofficial) Ruby Style Guide:
Avoid explicit use of the case equality operator ===. As it name implies it's meant to be used implicitly by case expressions and outside of them it yields some pretty confusing code.
# bad
Array === something
(1..100) === 7
/something/ === some_string
# good
something.is_a?(Array)
(1..100).include?(7)
some_string =~ /something/
Thanks, thenickperson. I'd follow that recommendation.