Don't understand hashing...

  • Thread starter Michael Neumann
  • Start date
M

Michael Neumann

Hi,

Don't know why this happens:

class Lazy
self.methods.reject{|m| m =~ /^__(.*)__$/}.each {|m|
eval "def #{m}(*args, &block) __getobj__.send:)'#{m}', *args, &block) end"
}

def initialize(&block)
@block = block
end

def __getobj__
if @block
@value = @block.call(*@args)
@block = nil
end
return @value
end

def method_missing(id, *args, &block)
__getobj__.send(id, *args, &block)
end

def hash
__getobj__.hash
end
end

id1 = Lazy.new {:Id}
id2 = :Id

p id1.hash == id2.hash # => true

h1 = {}
h2 = {}
h1[id1] = "id1"
h2[id2] = "id2"

p h1[id2] # => nil (expect: "id1")
p h2[id1] # => "id2"

I would have expected "id1" for h1[id2].
Can someone enlighten me?

Thanks.

Michael
 
R

Robert Klemme

Michael Neumann said:
Hi,

Don't know why this happens:

class Lazy
self.methods.reject{|m| m =~ /^__(.*)__$/}.each {|m|
eval "def #{m}(*args, &block) __getobj__.send:)'#{m}', *args, &block) end"
}

def initialize(&block)
@block = block
end

def __getobj__
if @block
@value = @block.call(*@args)
@block = nil
end
return @value
end

def method_missing(id, *args, &block)
__getobj__.send(id, *args, &block)
end

def hash
__getobj__.hash
end
end

id1 = Lazy.new {:Id}
id2 = :Id

p id1.hash == id2.hash # => true

h1 = {}
h2 = {}

Did you really mean to use two hashes?

robert

h1[id1] = "id1"
h2[id2] = "id2"

p h1[id2] # => nil (expect: "id1")
p h2[id1] # => "id2"

I would have expected "id1" for h1[id2].
Can someone enlighten me?

Thanks.

Michael
 

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
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top