The equal? method is defined by Object to test whether two values refer to exactly the same object. For any two distinct objects, this method always returns false:
ruby-1.9.2-p290 :009 > a = "hello" => "hello" ruby-1.9.2-p290 :010 > b = c = "hello" => "hello" ruby-1.9.2-p290 :011 > a.equal? b => false ruby-1.9.2-p290 :012 > b.equal? c => true
By convention, subclasses never override the equal? method.
Another way to determine if two objects are, in fact, the same object is to check their object_id :
a.object_id == b.object_id # Works like a.equal?(b)
The == operator is the most common way to test for equality. In the Object class, it is simply a synonym for equal? , and it tests whether two object references are identical.
Most classes redefine this operator to allow distinct instances to be tested for equality:
ruby-1.9.2-p290 :013 > a = "hello" => "hello" ruby-1.9.2-p290 :014 > b = c = "hello" => "hello" ruby-1.9.2-p290 :015 > a == b => true
The eql? method is defined by Object as a synonym for
that override it typically use it as a strict version of == that
does no type conversion.
ruby-1.9.2-p290 :019 > 1 == 1.0 => true ruby-1.9.2-p290 :020 > 1.eql? 1.0 => false
The Hash class uses eql? to check whether two hash keys are equal.
If two objects are
eql?, their hash
methods must also return the
The === operator is commonly called the case equality operator and is used to test whether the target value of a case statement matches any of the when clauses of that statement.
=== to test whether a value falls within the range.
ruby-1.9.2-p290 :021 > (1..10) === 5 => trueRegexp defines
===to test whether a string matches the regular expression.
ruby-1.9.2-p290 :022 > /\d+/ === "a432b" => true ruby-1.9.2-p290 :023 > /\d+/ === "acb" => falseAnd Class defines
===to test whether an object is an instance of that class.
ruby-1.9.2-p290 :024 > String === 's' => true ruby-1.9.2-p290 :025 > String === 32 => false
The =˜ operator is defined by String and Regexp (and Symbol in Ruby 1.9) to perform pattern matching.
Casiano Rodriguez León 2015-01-07