Converting hash values into keys

Create an empty hash called ‘dogs’: 

irb(main):001:0> dogs = {}

=> {}

Enter the keys and values for dogs (‘compton’ is key, ‘doodle’ is value):

irb(main):002:0> dogs[‘compton’] = :doodle

=> :doodle

irb(main):003:0> dogs[‘hazel’] = :doodle

=> :doodle

irb(main):004:0> dogs[‘ebi’] = :maltese

=> :maltese

irb(main):005:0> dogs[‘cub’] = :coton

=> :coton

irb(main):006:0> dogs[‘walle’] = :havanese

=> :havanese

Show the key-value pairs for the hash: 

irb(main):007:0> dogs

=> {“compton”=>:doodle, “hazel”=>:doodle, “ebi”=>:maltese, “cub”=>:coton, “walle”=>:havanese}

Create a new hash called ‘breeds’ that sets the default values for all pairs at 0: 

irb(main):008:0> breeds =

=> {}

Convert the values for ‘dogs’ into keys for the new ‘breeds’ hash  (‘count’ will be the values): 

irb(main):009:0> dogs.values.each { |count| breeds[count] += 1 }

=> [:doodle, :doodle, :maltese, :coton, :havanese]

Show the key-value pairs for ‘breeds’: 

irb(main):010:0> breeds

=> {:doodle=>2, :maltese=>1, :coton=>1, :havanese=>1}

Converting hash values into keys

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s