From: Martin DeMello Date: 2002-04-15T07:21:15+09:00 Subject: Re: Reverse hash lookup? Alex Liebowitz wrote: > Is there any way to specify a value and hash, and get the key corresponding > to that value (in O(1) time, preferably)? How would this work in the case of more than one key having the same value? Anyway, the following (untested) hack should work if you don't mind having reverse just returning the last key to be assigned a particular value: class InvertibleHash < Hash def initialize(*args) super(*args) @reverse = self.invert end def []=(key, val) super(key, val) @reverse[val] = key end def reverse_lookup(val) @reverse[val] end end or, enforcing a 1-1 mapping: class Bijection < Hash def initialize(*args) super(*args) @reverse = self.invert end def []=(key, val) super(key, val) if @reverse.has_key?(val) self.delete(@reverse[val]) end @reverse[val] = key end def reverse_lookup(val) @reverse[val] end end -- Martin DeMello