Differences between equals?, eql?, ===, and ==

Asked 1 years ago, Updated 1 years ago, 86 views

Find out the differences between equals?, eql?, ===, and ==.

What we've found so far is

I haven't figured out what eql? is doing with default yet, and I'm not sure I just looked through it.

Ruby has many ways to compare the same, so it's confusing what's what <

ruby operator compare

2022-09-21 21:22

1 Answers

If you really want to know exactly, you should watch Object documentation on ruby-doc.org.

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.

From an object perspective, == returns true when two objects are equal. Usually, this method can be overridden in a child class, and it is implemented differently for each class.

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

Similar to #==. I usually override it to write in a case statement.

case some_object
when /a regex/
  # # The regex matches
when 2..4
  # # some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
  # # the lambda returned true
end

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?

Returns true when two objects have the same hash. Between class objects, eql? is equal to == This property is also maintained in Subclass except for classes associated with numbers.

#Number is different between == and eql?
1 == 1.0     #=> true
1.eql? 1.0   #=> false

Unlike ==, the equal? method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

Unlike ==, the equal? method cannot be overridden by subclass. This is because equal? compares the identity of the object.

irb(main):027:0> m = "a"
=> "a"
irb(main):028:0> n = "a"
=> "a"
irb(main):029:0> m.Equal false, but values such as (n)? #
=> false
irb(main):030:0> 
Irb n 031:0 : (main) * = m such objects. # now m n
=> "a"
irb(main):032:0> m.equal?(n)
=> true
irb(main):033:0> 


2022-09-21 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.