How do I swap keys and values in a Hash?
I have the following Hash:
{:a=>:one, :b=>:two, :c=>:three}
that I want to transform into:
{:one=>:a, :two=>:b, :three=>:c}
Using map seems rather tedious. Is there a shorter solution?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Ruby has a helper method for Hash that lets you treat a Hash as if it was inverted (in essence, by letting you access keys through values):
If you want to keep the inverted hash, then Hash#invert should work for most situations:
BUT…
If you have duplicate values,
invertwill discard all but the last occurrence of your values (because it will keep replacing new value for that key during iteration). Likewise,keywill only return the first match:So, if your values are unique you can use
Hash#invert. If not, then you can keep all the values as an array, like this:Note: This code with tests is now on GitHub.
Or: