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
http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-case http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and
Tweet