Skip to content

Instantly share code, notes, and snippets.

@mtodd
Created September 23, 2008 19:19
Show Gist options
  • Save mtodd/12368 to your computer and use it in GitHub Desktop.
Save mtodd/12368 to your computer and use it in GitHub Desktop.

With Reverse Lookup

Extends Hashes with the ability to look up by key or value instead of just key.

The benefit of this construct is mostly (and usually only) beneficial when there’s
a clear deliniation between the keys and values, such as with hashes with a common
key scheme and uniquely different string values. For example, a hash of states
(both geologic and status), etc.

It is not recommended to use this library with dynamically consumed data as
conflicts can occur and behavior is not guaranteed to work sanely or consistently
at that point (though it should still work).

License & Copyright

Copyright 2008 Matt Todd, Highgroove Studios

Licensed under the MIT License.

# Useful for defining a hash a single way and being able to look up by key or
# value. For instance:
#
# hash = {
# 1 => :foo,
# 2 => :bar
# }.extend(WithReverseLookup)
#
# hash[1] #=> :foo
# hash[:foo] #=> 1
#
module WithReverseLookup
def [](key)
if self.keys.include?(key)
super
else
self.each do |(index, value)|
return index if value == key
end
return nil
end
end
end
#--
# Specs
#++
if __FILE__ == $0
puts "Running tests..."
puts ""
# setup test data
hash = {
1 => :yes,
0 => :no
}
puts "Test data: #{hash.inspect}"
puts ""
# extend hash
hash.extend(WithReverseLookup)
# run test 1
puts "1. Should find hash[1] as :yes"
puts hash[1] == :yes ? 'PASS' : 'FAIL'
puts ""
# run test 2
puts "2. Should find hash[0] as :no"
puts hash[0] == :no ? 'PASS' : 'FAIL'
puts ""
# run test 3
puts "3. Should find hash[2] as nil"
puts hash[2] == nil ? 'PASS' : 'FAIL'
puts ""
# run test 4
puts "4. Should find hash[:yes] as 1"
puts hash[:yes] == 1 ? 'PASS' : 'FAIL'
puts ""
# run test 5
puts "5. Should find hash[:no] as 0"
puts hash[:no] == 0 ? 'PASS' : 'FAIL'
puts ""
# run test 4
puts "4. Should find hash[:foo] as nil"
puts hash[:foo] == nil ? 'PASS' : 'FAIL'
puts ""
puts "Finished."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment