我正在尝试在将值减去3后更新哈希值。例如,
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
如何返回包含键和新值的整个散列?
最佳答案
在块中,确保使用=
修改散列:
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
前面加上下划线,表示该变量未在块中使用。关于ruby - 更新哈希值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53843659/