I need a bidirectional Hash table in Ruby. For example:
h = {:abc => 123, :xyz => 789, :qaz => 789, :wsx => [888, 999]}
h.fetch(:xyz) # => 789
h.rfetch(123) # => abc
h.rfetch(789) # => [:xyz, :qaz]
h.rfetch(888) # => :wsx
Method rfetch
means reversed fetch and is only my proposal.
Note three things:
- If multiple keys map at the same value then
rfetch
returns all of them, packed in array. - If value is an array then
rfetch
looks for its param among elements of the array. - Bidirectional Hash means that both
fetch
andrfetch
should execute in constant time.
Does such structure exists in Ruby (including external libraries)?
I thought about implementing it using two one-directional Hashes synchronized when one of them is modified (and packing it into class to avoid synchronization problems) but maybe I could use an already existing solution?
hash.invert()
to make a separate inverse hash (https://mcmap.net/q/116453/-how-to-find-a-hash-key-containing-a-matching-value). As @ken-bloom points out, a more robust implementation of this is at raa.ruby-lang.org/project/inverthash – Jacobjacoba