defining key equivalence in a hash

S

Suraj Kurapati

Hello,

I'm trying to make two keys equivalent by having their #hash method
produce the same result. But this does not seem to work:

irb(main):001:0> class K; def hash; 90; end; end
=> nil
irb(main):002:0> h = {}
=> {}
irb(main):003:0> h[K.new] = 1
=> 1
irb(main):004:0> h.key? K.new # <---- I want this to return true!
=> false

What am I missing?

Thanks for your consideration.
 
D

Daniel Finnie

If you put K.new into a variable, and then check for that, it will
return true:

irb(main):001:0> class K; def hash; 90; end; end
=> nil
irb(main):002:0> h = {}
=> {}
irb(main):003:0> k = K.new
=> #<K:0xb7cac4ac>
irb(main):004:0> h[k] = 1
=> 1
irb(main):005:0> h[k]
=> 1
irb(main):006:0> h.key? k
=> true

It's because K.new creates a new location in memory for each call to it,
but h.key? checks the location in memory, not the contents of the keys
and the objects passed to it. So if you call K.new twice, each will
return a new location in memory.

Dan
 
E

Eric Hodel

Hello,

I'm trying to make two keys equivalent by having their #hash method
produce the same result. But this does not seem to work:

irb(main):001:0> class K; def hash; 90; end; end
=> nil
irb(main):002:0> h = {}
=> {}
irb(main):003:0> h[K.new] = 1
=> 1
irb(main):004:0> h.key? K.new # <---- I want this to return true!
=> false

What am I missing?

class K; def eql?(other) true; end; end

#eql? is called if o1.hash == o2.hash. If #eql? returns true the
objects belong to the same index.
 
A

ara.t.howard

Hello,

I'm trying to make two keys equivalent by having their #hash method
produce the same result. But this does not seem to work:

irb(main):001:0> class K; def hash; 90; end; end
=> nil
irb(main):002:0> h = {}
=> {}
irb(main):003:0> h[K.new] = 1
=> 1
irb(main):004:0> h.key? K.new # <---- I want this to return true!
=> false

What am I missing?

K#eql?

for example


harp:~ > cat a.rb
class K
attr 'key'
def initialize() @key = 42 end
def hash() @key.hash end
def eql?(other) other.key == @key end
end

p K.new => 'which', K.new => 'one'


harp:~ > ruby a.rb
{#<K:0xb75cca34 @key=42>=>"one"}

regards.

-a
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top