简体   繁体   中英

Hash with array keys to simple hash of hashes

Is there an easy way to transform the first one to the second one ? This comes from two successive ActiveRecord .group() method.

1) sales = {["USD", 11]=>0.158148e4, ["USD", 10]=>0.35248e3, ["EUR", 10]=>0.3508e3}

2) sales = {"USD": { 11 =>0.158148e4, 10 => 0.35248e3}, "EUR": { 10 =>0.3508e3}}

You can use Enumerable#each_with_object :

sales.each_with_object(Hash.new { |k,v| k[v] = {} }) do |((f, s), v), memo| 
  memo[f][s] = v 
end
#=> {"USD"=>{11=>1581.48, 10=>352.48}, "EUR"=>{10=>350.8}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM