Reputation: 653
As per definition, equal?
checks if the two objects are same, where as eql?
checks if the class are same and values are same.
x = 'hi'
y = 'hi'
x.equal? y # => false
x.eql? y # => true
x = 1
y = 1
x.equal? y # => true
x.eql? y # => true
Why is the second x.equal? y
true
? Aren't x
and y
two instances of Fixnum
? Why doesn't it apply to Fixnum
/Float
as shown in the examples above?
Upvotes: 0
Views: 132
Reputation: 1263
I know this question already has been answered but I'll add this about object_id's
my_string << 'something'
and my_string.replace 'something'
and bang methods like my_string.strip!
don't change the object_id that's why you can change a constant's content like MyString = 'test'
But MyString.freeze
will prevent you from the constant beeing mutable.
It's good to try things like this to learn the language :
irb(main):024:0> x = '1'
=> "1"
irb(main):025:0> y = x
=> "1"
irb(main):026:0> x.equal? y
=> true
irb(main):027:0> x << 'test'
=> "1test"
irb(main):028:0> y
=> "1test"
irb(main):029:0> nope = nope
=> nil
Upvotes: 0
Reputation: 76
Because x
and y
do actually refer to the exact same object. Unlike strings, each integer value has only one instance at any given time.
Reference: http://ruby-doc.org/core-2.2.1/Fixnum.html
There is effectively only one Fixnum object instance for any given integer value [...]
Edit: To make it a bit more clear, you might want to look at the object_id for these objects:
irb(main):001:0> x = 1
=> 1
irb(main):002:0> y = 1
=> 1
irb(main):003:0> x.object_id
=> 3
irb(main):004:0> y.object_id
=> 3 # Same ID as above
irb(main):005:0> x = 'hi'
=> "hi"
irb(main):006:0> y = 'hi'
=> "hi"
irb(main):007:0> x.object_id
=> 70287051883000
irb(main):008:0> y.object_id
=> 70287051869720 # Different ID than X
Upvotes: 5