Hash and "=="

Hello all,

In the Java world when one overrides "equals" in a class it is also
necessary to override "hashCode" so that objects behave properly in
collections. Does the same apply in the Ruby world, ie, it is
necessary to override "hash" when overriding "=="?

Are there helper idioms or libraries in Ruby to assist in constructing
"==" and "hash" methods (comparable to Java's Jakarta commons
HashCodeBuilder and EqualsBuilder)?

Thanks,

--Brian

Hello all,

In the Java world when one overrides "equals" in a class it is also
necessary to override "hashCode" so that objects behave properly in
collections. Does the same apply in the Ruby world, ie, it is
necessary to override "hash" when overriding "=="?

You'll need to define #hash and #eql? as well.

Are there helper idioms or libraries in Ruby to assist in constructing
"==" and "hash" methods (comparable to Java's Jakarta commons
HashCodeBuilder and EqualsBuilder)?

If its a wrapper object, I usually pass through to the wrapper. If its a composite object something like ^ ing all the components hashes together works.

Its not hard enough that you need an extra library.

You'll want to define #<=> and include Comparable if you want to sort your objects sensibly.

···

On 13 Sep 2005, at 04:33, Brian Buckley wrote:

--
Eric Hodel - drbrain@segment7.net - http://segment7.net
FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04

What is the difference between "eql?" and "==" in Ruby?

Brian Buckley wrote:

What is the difference between "eql?" and "==" in Ruby?

Type conversion for numeric values:

1.eql? 1.0

=> false

1 == 1.0

=> true

But most of the time they behave equivalently.

"a".eql? "a"

=> true

"a" == "a"

=> true

Kind regards

    robert

#eql? is only used by Hash to determine if two keys (#hash) collide. Usually it just calls #==.

if object1.hash == object2.hash and object1.eql? object2 then
   # both objects occupy the same slot in a Hash
else
   # the objects occupy different slots in a Hash
end

···

On 15 Sep 2005, at 07:50, Brian Buckley wrote:

What is the difference between "eql?" and "==" in Ruby?

--
Eric Hodel - drbrain@segment7.net - http://segment7.net
FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04