From: Jean-Hugues ROBERT Date: 2004-04-26T19:23:40+09:00 Subject: Re: IdentityHash, like Hash but with keys using equals? vs eql? At 10:01 25/04/2004 +0900, you wrote: >On Thu, 8 Apr 2004 14:00:26 +0900, Jean-Hugues ROBERT wrote: > > At 07:44 08/04/2004 +0900, you wrote: > >> Jean-Hugues ROBERT writes: > >>> BTW: I need that to detect "true" circular paths when walking a > >>> tree/graph. Rigth now I detect false circulars when nodes' values > >>> compare equal where in fact it is two different node objects (with > >>> the same "value"). > >> Can you just hash the ids? > >> hash[obj.id] = blah > > Yes ! > > So: an IdentityHash in ruby is just a Hash, but > > with obj.object_id() in it vs the obj itself. > > Makes a lot of sense. > > Thanks George ! > > > > Jean-Hugues > > PS: As one said, in Computer Science everything is solvable by adding one > > indirection level. > >class IdentityHash < Hash > def [](k) > super k.object_id > end > > def []=(k, v) > super k.object_id, v > end >end > >Note that this will, of necessity, prevent this from doing anything >meaningful: > > i = IdentityHash.new > i["abc"] = "def" > puts i["abc"] # => nil > >-austin Many thanks austin. a = "abc" i = IdentityHash.new i[a] = "def" puts i[a] # => "def" ! That is exactly what an IdentityHash should do. In my case, I use it more like this visited = IdentityHash.new def walk( graph, &block ) for node in graph do next if visited[node] # Avoid circular path visited[node] = true block.yield node walk( node, &block) if node.respond_to: each end end Thanks again Austin. Jean-Hugues >-- >austin ziegler * austin@halostatue.ca * Toronto, ON, Canada >software designer * pragmatic programmer * 2004.04.24 > * 20.57.28 ------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17