Where developers come to connect, share, build and be inspired.

103

The rarely used === in Ruby

12933 views

=== 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

Comments

Add a comment