Hash examples

Hash of Arrays

example, need to group sport stars according to their sport

visual representation of data, we will convert this into a Hash data structure

store this data in config file

Michael Jordan = NBA

Larry Bird = NBA

Mark Messier = NHL

etc

# now lets create the Hash of Arrays

# the parent 'sports' is a Hash (key/val pair). Each element in that Hash is an Array that holds the names of players,

# array is better than a simple Hash because you can store multiple values for each hash Key

# the final data structure should look like this

print sports[NBA]

Michael Jordan, Larry Bird

# create new parent Hash

sports = Hash.new()

parse the config and for each player, add him to the sport Hash

players = [ 'Michael Jordan', 'Larry Bird', etc ]

players.each do |player|

sport = get_config(player) # some function, returns the sport by reading config file

# if Array element doesnt exist, create it (will only happen once for 1st Player element)

if not sports[sport].is_a?(Array)

sports[sport] = Array.new()

end

# now push the Player name into the Sport's Array

sports[sport].push(player)

end

# lets print out all the key + value pairs

sports.each do | sport, player |

puts sport, player

end

NBA, Michael Jordan

NBA, Larry Bird

NHL, Mark Messier

etc

Hash of Hashes

some data needs to be stored in a multidimensional Hash, aka Hash of Hashes, for example

lets store a list of countries, for each country we will have a Capital City, Population Size and Country Code

visual representation of data,

visually this data looks like this in a Hash of Hashes

countries['United States'] = {

'capital' => 'Washington',

'population' => '310,000,000',

'code' => 'US',

}

# create new parent Hash

countries = Hash.new()

parse the config and for each country, add to Hash

country_list = [ 'United States', 'United Kingdom', etc ]

country_list.each do |country|

capital = get_country(country) # some function, returns the country capital by reading config file

pop = get_pop(country) # some function, returns the country population by reading config file

code = get_code(country) # some function, returns the country code by reading config file

# now push the Capital name into the Country hash

countries[country]['capital'] = capital

# now push the Population name into the Country hash

countries[country]['population'] = pop

# now push the Code name into the Country hash

countries[country]['code'] = code

end

# lets print some values

puts countries['United States']['capital']

=> Washington

puts countries['Israel']['population']

=> 8,000,000

puts countries['France']['code']

=> FR

etc