我有一个哈希
original_hash = {"10"=>3, "15"=>2, "20"=>1}
我想创建一个新的哈希,调用它results_hash
,其中的键original_hash
将附加'$'
符号,键的新值将是original_hash
. 生成的results_hash
应该是:
results_hash = {"$10"=>30, "$15"=>30, "$20"=>20}
我怎样才能做到这一点?
resulted_hash = {}
original_hash.each do |key, val|
resulted_hash["$" + k] = v*k.to_i
end
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}