Ruby hash with multiple keys pointing to the same value
ruby
Solution
You could subclass hash and override `[]` and `[]=`.
class AliasedHash < Hash
def initialize(*args)
super
@aliases = {}
end
def alias(from,to)
@aliases[from] = to
self
end
def [](key)
super(alias_of(key))
end
def []=(key,value)
super(alias_of(key), value)
end
private
def alias_of(key)
@aliases.fetch(key,key)
end
end
ah = AliasedHash.new.alias(:bar,:foo)
ah[:foo] = 123
ah[:bar] # => 123
ah[:bar] = 456
ah[:foo] # => 456
Problem
I am looking for a way to have, I would say synonym keys in the hash. I want multiple keys to point to the same value, so I can read/write a value through any of these keys. As example, it should work like that (let say :foo and :bar are synonyms) ``` hash[:foo] = "foo" hash[:bar] = "bar" puts hash[:foo] # => "bar" ``` Update 1 Let me add couple of details. The main reason why I need these synonyms, because I receive keys from external source, which I can't control, but multiple keys could actually be associated with the same value.