June 2017
Beginner
330 pages
7h 30m
English
Next, we are going to see how to reverse the key/value pair values. For our example, let's imagine that we want to swap out the hash so that the age is the key and the name is the value.
One way to do is to iterate through each pair, store it in a variable, swap them, and update. But, that's slow and more tedious. A better and easier way would be to leverage Ruby's invert method:
people.invert
This does the swapping work for us:
{32=>:jordan, 27=>:tiffany, 10=>:kristine, 29=>:heather, 42=>:leann}
This method can be particularly useful if you want to store the inverted values into a new hash, which we can do with code, like the following:
people_2 = people.invert
Read now
Unlock full access