Friday, January 8, 2010

Section 7.2. Accessing Hashes


Hashes > Accessing Hashes




7.2. Accessing Hashes


Here's a hash that associates zip codes with the names of towns in Wyoming that start with the letter T (had to limit it somehow):

zip = { 82442 => "Ten Sleep", 83025 => "Teton Village", 83127 => "Thayne",
82443 => "Thermopolis", 82084 => "Tie Siding", 82336 => "Tipton", 82240 =>
"Torrington", 83110 => "Turnerville", 83112 => "Turnerville" }


There are tons of ways to access keys and/or values from a hash. You can pick what works for you—what works for the task at hand.


You can test to see if the hash zip has a given key with any of the following methods, which are all synonyms of each other: key?, has_key?, member?, or include?:

zip.has_key? 82442 # => true


Or you can do the flip side, and see if it has a given value with value? or has_value?:

zip.has_value? "Ten Sleep" # => true


Let's start pulling stuff out of zip. Here is a simple way of grabbing a value: the [] method. It retrieves a single hash value based on a key:

zip[82442] # => "Ten Sleep"


Then we have the methods keys and values. Return an array containing all the keys in a hash with keys:


zip.keys # => [83110, 83127, 82336, 83112, 82084, 83025, 82442, 82443, 82240]




Get an array with all the values from a hash with values:

zip.values # => ["Turnerville", "Thayne", "Tipton",
"Turnerville", "Tie Siding", "Teton Village", "Ten Sleep", "Thermopolis",
"Torrington"]


Retrieve the values out of a hash based on one or more keys with values_at, also placing the value or values in an array:


zip.values_at 82084 # => ["Tie Siding"]
zip.values_at 82442, 82443, 82240 # => ["Ten Sleep", "Thermopolis", "Torrington"]




Now return a value for a given key (one key only) with the index method:

zip.index "Thayne" # => 83127


The select method uses a block to return a new, multidimensional array of key-value pairs:


zip.select { |key,val| key > 83000 } # => [[83110,
"Turnerville"], [83127, "Thayne"], [83112, "Turnerville"], [83025, "Teton Village"]]




 

 


No comments: