53xawg
14.44K
· October 2013 ·
2014 07 31 18.14.34 hdr

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
Sign in or sign up to add your response.

4 Responses

10064
2014 07 31 18.14.34 hdr

Credit to http://stackoverflow.com/users/23649/jtbandes for explaining some of these concepts on StackOverflow

over 1 year ago ·
10110
55724162c14cb41ce6c0ae219a6656c2 normal

Class objects implement === as "is_a?". Which is kind of neat for case statements, but also has a couple of gotchas:

http://johnleach.co.uk/words/402/rubys-case-statement-uses

over 1 year ago ·
10155
Ness

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/
over 1 year ago ·
10162
Img 0739 2

Thanks, thenickperson. I'd follow that recommendation.

over 1 year ago ·
Featured Programming Job

Software Developer
·
Chicago, IL
·
Full Time
Search all programming jobs