0
  def self.foo
    [
      ["a","aa"],
      ["b","bb"],
    ]
  end

Given "a", I should be able to retrieve "aa" Given "bb", I should be able to retrieve "b"

How do I do this?

2
  • 1
    What prevents from making a normal hash out of this? Commented Sep 12, 2012 at 13:28
  • This datastructure is called a bi-directional map, bidimap, bimap. Maybe you can find a Ruby implementation somewhere, but it doesn't look good. Commented Sep 12, 2012 at 13:55

3 Answers 3

2

assoc and rassoc are your friends:

ar = [
  ["a","aa"],
  ["b","bb"],
]
p ar.assoc("a").last #=> "aa"
p ar.rassoc("bb").first #=> "b"
Sign up to request clarification or add additional context in comments.

Comments

0
Hash[self.foo].invert["bb"] #=> "b"
Hash[self.foo]["a"] #=> "aa"

Hash[] turns array into hash

Hash#invert inverts the hash so all values map to the keys

If you want to do both:

Hash[self.foo]["bb"] or Hash[self.foo].invert["bb"] #=> "b"

Comments

0

I would create my own "bimap" implementation, perhaps something like:

class Bimap < Hash
  alias :__put__ :[]=
  def []=(key,value)
    __put__(key,value)
    __put__(value,key)
  end

  alias :__size__ :size
  def size
    __size__ / 2
  end

  # ...any other Hash methods to reimplement?
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.