1

我有一个哈希

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

我想创建一个新的哈希,调用它results_hash,其中的键original_hash将附加'$'符号,键的新值将是original_hash. 生成的results_hash应该是:

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

我怎样才能做到这一点?

4

2 回答 2

2
resulted_hash = {}

original_hash.each do |key, val|
 resulted_hash["$" + k] = v*k.to_i
end
于 2013-11-07T10:51:58.463 回答
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}
于 2013-11-07T10:44:19.147 回答