Ruby has 4 comparison methods, equal, eql, = =, = =, and behaves differently in different classes. In the use of time is also particularly easy to confuse. This blog post will demonstrate some code to explain each method.
= =-Class sense equality, requires each class to define its own implementation
To see whether two objects are the same in a particular class, you need to look at the logical representation of the business, all of which the programmer overrides the definition of the method to determine whether two objects are the same.
For example, the string class is about whether the actual text string is the same, rather than whether it comes from the same memory area.
>> a = "abc"
#=> "abc"
>> B = A + ""
#=> "abc"
?> a = = B
#=> true
>> a.object_id
#=> 70255156346640
>> b.object_id
#=> 70255156340640
= = = The method that is invoked when used in a case statement
This method is usually invoked in case comparison, such as
Case Some_object
when/a regex/
# The Regex matches when
string
# Some_object is kind of string
W Hen 2..4
# some_object ' in ' range 2..4 when
lambda {|x| some_crazy_custom_predicate}
# the lambda ret urned True End
Equal to
if/a regex/= = Some_object
# The Regex matches
elsif String = = Some_object
# some_object is kind of object< C4/>elsif (2..4) = = Some_object # Some_object is in the
range 2..4
elsif lambda {|x| some_crazy_custom_predicate } = = = Some_object
# The Lambda returned true end
Eql? -The usual sense of equality
If the value of two objects is the same and returns True, if you redefine the = = method of the subclass, you generally need to alias to EQL? Method. Of course, there are exceptions, the return values of two methods are different for integers and decimals.
1 = = 1.0 #=> true
1.EQL 1.0 #=> False
Eql? Used in Hash to do member value comparisons
[1] Pry (main) > hash = hash.new
#=> {}
[2] Pry (main) > Hash[2] = "a"
#=> "a"
[3] Pry (main) > H ASH[2.0] = "B"
#=> "B"
[4] Pry (main) > Hash[2]
#=> "A"
[5] Pry (main) > hash[2.0]
#=> " B "
[6] Pry (main) > hash[2.00] =" C "
#=>" C "
[7] Pry (Main) > hash[2.0]
#=>" C "
So when you should cover this method, see how you want him to behave in Hash comparison.
Equal? -Objects with the same memory address
This method should not cover the quilt class
Compares whether two objects are the same in memory and whether they have the same object_id value
The same object in time in Rails
Q = User.first
User Load (40.4ms) Select Users. * from ' users ' order by ' users '. ID "ASC LIMIT 1
#=> #<user id:1, email:" Ryan@wongyouth.com ">
q2 = User.first
User Load (0.4ms) S Elect "users". * from ' users ' order by ' users '. ID "ASC LIMIT 1
#=> #<user id:1, email:" Ryan@wongyouth.com ">
q.equal? Q2 #=>
False
Memory methods
- = = Overrides the method
- = = When overriding the case statement by business requirements
- eql? Alias to = = method, when required override method to change Hash comparison performance
- equal? Do not change