我正在尝试将值减去三后更新哈希值。例如,
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
}
我有这段代码,它将值减去三:
extinct_animals.each {|animal, year| puts year - 3}
和输出:
1911
1933
1887
1659
1920
如何返回带有键和新值的整个哈希?
答案 0 :(得分:5)
您将要使用Hash#transform_values!,它在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}
答案 1 :(得分:0)
在该块内,确保您正在使用=
修改哈希:
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
}
请勿使用puts
。只是写到控制台。
此解决方案的更简短版本为:
extinct_animals.each { |animal, _year| extinct_animals[animal] -= 3 }
我们在year
前面加一个下划线,以指示该变量未在块内使用。