jmk929
jmk929

Reputation: 45

Update values in a hash

I am trying to update my hash's values after subtracting the values by three. For example,

extinct_animals = {
  "Passenger Pigeon" => 1914,
  "Tasmanian Tiger" => 1936,
  "Eastern Hare Wallaby" => 1890,
  "Dodo" => 1662,
  "Pyrenean Ibex" => 2000,
  "West African Black Rhinoceros" => 2011,
  "Laysan Crake" => 1923
}

I have this code, which sets the values to subtract three:

extinct_animals.each {|animal, year| puts year - 3}

and the output:

1911
1933
1887
1659
1920

How do I return the entire hash with the keys and new values?

Upvotes: 2

Views: 98

Answers (2)

anothermh
anothermh

Reputation: 10526

Within the block, make sure you are modifying the hash by using =:

extinct_animals.each { |animal, year| extinct_animals[animal] = year - 3 }
=> {
  "Passenger Pigeon" => 1911,
  "Tasmanian Tiger" => 1933,
  "Eastern Hare Wallaby" => 1887,
  "Dodo" => 1659,
  "Pyrenean Ibex" => 1997,
  "West African Black Rhinoceros" => 2008,
  "Laysan Crake" => 1920
}

Don't use puts. That just writes out to the console.

A more brief version of this solution would be:

extinct_animals.each { |animal, _year| extinct_animals[animal] -= 3 }

Here we prefix year with an underscore to indicate that the variable is not used within the block.

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

You'll want to use Hash#transform_values!, which made its debut in MRI v2.4:

extinct_animals.transform_values! { |v| v - 3 }
  #=> {"Passenger Pigeon"=>1911, "Tasmanian Tiger"=>1933,
  #    "Eastern Hare Wallaby"=>1887, "Dodo"=>1659, "Pyrenean Ibex"=>1997,
  #    "West African Black Rhinoceros"=>2008, "Laysan Crake"=>1920}

extinct_animals
  #=> {"Passenger Pigeon"=>1911, "Tasmanian Tiger"=>1933,
  #    "Eastern Hare Wallaby"=>1887, "Dodo"=>1659, "Pyrenean Ibex"=>1997,
  #    "West African Black Rhinoceros"=>2008, "Laysan Crake"=>1920}

Upvotes: 5

Related Questions