Today I Learned

hashrocket A Hashrocket project

Ruby Threequals

Ruby's == is pretty straightforward. From the Object class documentation:

Equality — At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Some examples from the String class:

irb > 'foo' == 'foo'
 => true
irb > 'foo' == :foo
 => false
irb > 'foo' == 'bar'
 => false

The triple equals, ===, sometimes called a ‘threequals’ or ‘case equality operator’, is different (again from the Object docs):

Case Equality – For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

The threequals compares the type of two arguments. One way to think about a === b is: 'does b belong in a box a’?

A few examples:

irb > String === 'foo'
 => true
irb > Array === %w(one two three)
 => true
irb > Range === (1..10)
 => true
irb > /car/ === 'carpool'
 => true

All of these evaluate false when the == operator is used.

Ruby's case statement operator uses the threequals for its control flow.

h/t Chris Erin

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.