通过迭代哈希来构建新哈希。最优雅的方式?

时间:2011-05-03 00:38:35

标签: ruby hash

必须有比这更优雅的方式吗?

rates = { 40 => 2.75, 25 => 3.25, 15 => 4.75 }

effective_rates = {}
rates.each do |depos, rate|
  effective_rates[depos] = rate/1200
end

3 个答案:

答案 0 :(得分:4)

右。

rates = { 40 => 2.75, 25 => 3.25, 15 => 4.75 }
effective_rates = Hash[rates.map{|depos, rate| [depos, rate/1200]}]
# => {40=>0.0022916666666666667, 25=>0.0027083333333333334, 15=>0.003958333333333334}

答案 1 :(得分:3)

effective_rates = rates.inject({}) { |m, (k,v)| m[k] = v/1200; m }

答案 2 :(得分:3)

effective_rates = rates.merge(rates){|depos, rate| rate/1200}