改变哈希

时间:2013-11-07 10:42:11

标签: ruby hash

我有一个哈希

original_hash = {"10"=>3, "15"=>2, "20"=>1}

我想制作一个新的哈希,称之为results_hash,其中original_hash的键将附加'$'符号,键的新值将为(键*值) )original_hash。生成的results_hash应为:

results_hash = {"$10"=>30, "$15"=>30, "$20"=>20}

我该怎么做?

2 个答案:

答案 0 :(得分:2)

resulted_hash = {}

original_hash.each do |key, val|
 resulted_hash["$" + k] = v*k.to_i
end

答案 1 :(得分:1)

original_hash = {"10"=>3, "15"=>2, "20"=>1}
results_hash = Hash[original_hash.map { |k,v| ['$'+k,k.to_i*v] }]
p results_hash # => {"$10"=>30, "$15"=>30, "$20"=>20}

original_hash = {"10"=>3, "15"=>2, "20"=>1}
results_hash = original_hash.each_with_object({}) { |(k,v),h| h['$'+k]=k.to_i*v }
p results_hash # => {"$10"=>30, "$15"=>30, "$20"=>20}