Skip to content

Instantly share code, notes, and snippets.

@ehrenmurdick
Last active July 29, 2017 02:31
Show Gist options
  • Save ehrenmurdick/5eefd0a8e91cfb37fabb4cb20f8b3631 to your computer and use it in GitHub Desktop.
Save ehrenmurdick/5eefd0a8e91cfb37fabb4cb20f8b3631 to your computer and use it in GitHub Desktop.

Triple equals in ruby is really interesting!

ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]

You can check if an instance is in a class

class A
end

a = A.new
A === a
# true

But it is not communative

a === A
# false

You can check if a string matches a regex

/f/ === "foo"
# true

But again not the reverse

"foo" === /f/
# false

If objects are of the same class, it will check for equality

"string" === "string"
# true

a = "str"
b = "str"

a === b
# true

And if they are the same type, it falls back to regular equality

class A
  def ==(other)
    # this will get caled by ===
    true
  end
end
a = A.new
b = A.new

a === b
# true

You can use it to check if an item is included in a range

(1..10) === 5
# true

5 === (1..10)
# false

It's used under the covers by case statements

case "string"
when /s/
  puts "matches /s/"
when "string"
  puts "is equal to string"
when String
  puts "is an instance of string"
when ('a'..'zzzzzz')
  puts 'is between 1 and 5 alpha only characters'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment