Download - All Objects are created .equal?
All Objects Are Created .equal?Understand equality in your Ruby codez
github.com/gsterndale/equality
a == b
a === b
a.eql? b
a.equal? b
Equality methods
==
a == b
Everyday equality (==)
a = MyBasicClass.newb = MyBasicClass.new
a == b# => false
b = a
a == b# => true
Default ==
class RomanNumeral
def ==(other) if other.respond_to?(:to_f) self.to_f == other.to_f else false end end
end
Overriding ==
iv = RomanNumeral.new('IV')
iiii = RomanNumeral.new('IIII')
iv == iiii# => true
Overriding ==
===
a === b
case statement equality (===)
a = Object.newb = Object.new
case awhen b 'b must === a'else 'b must NOT === a'end# => "b must NOT === a"
Default ===
a = 1b = 1.0
case awhen b 'b must === a'else 'b must NOT === a'end# => "b must === a"
Float ===
case '123'when /\d+/ 'At least one number'else 'No numbers found'end# => "At least one number"
Regexp ===
/\d+/ == '123'# => false
/\d+/ === '123'# => true
When === != ==
case 'abc'when String 'It is a String!'else 'Not a String'end# => "It is a String!"
Class ===
/\d+/ === '123'# => true
'123' === /\d+/# => false
Asymmetry
2 === Integer# => false
Integer === 2# => true
Fixnum === 2# => true
Asymmetry
.equal?
a = 'FOO'b = a
a.equal? b# => true
a.equal? 'FOO'# => false
Object equality (.equal?)
.eql?
a.eql? b
Hash key equality (.eql?)
foo = Object.newhash = { foo => 'My value' }
bar = Object.new
foo.equal? bar# => false foo.eql? bar# => false
hash[bar]# => nil
Default .eql?
foo = 'My Key'hash = { foo => 'My value' }
bar = 'My Key'
foo.equal? bar# => false foo.eql? bar# => true
hash[bar]# => "My value"
String .eql?
class RomanNumeral
def eql?(other) other.kind_of?(RomanNumeral) && self.to_i.eql?(other.to_i) end
end
Overriding .eql?
iv = RomanNumeral.new('IV')
hash = { iv => 'Four' }
iiii = RomanNumeral.new('IIII')
iv.equal? iiii# => false iv.eql? iiii# => true
hash[iiii]# => "Four"
Overriding .eql?
Comparable
# You must define <=>a <=> b# => -1, 0, 1 -or- nil
a == b
a > ba < ba >= ba <= b
c.between?(a, b)
Comparison methods
class RomanNumeral
def <=>(other) if other.respond_to?(:to_f) self.to_f <=> other.to_f else nil end end
end
Overriding <=>
v = RomanNumeral.new('V')x = RomanNumeral.new('X')
v <=> x# => -1
v >= x# => false
RomanNumeral.new('VIII').between?(v, x)# => true
Overriding <=>
iv = RomanNumeral.new('IV')iiii = RomanNumeral.new('IIII')x = RomanNumeral.new('X')
[iv, x, iiii]# => [IV, X, IIII]
[iv, x, iiii].sort# => [IV, IIII, X]
Sorting Enumerables