我最终得到了10个CSV :: Row对象的数组。现在我想配对它们,因为每个对象中有2个具有相同的名称。现在我知道如何做到这一点,多循环的方式,它只是不优雅。任何人都有快速的1-2班轮来做这件事吗?
所以这是数组:
[#<CSV::Row "name":"eee.xxx" "time":"2014-10-31T15:35:14+00:00" "records":"98">,
#<CSV::Row "name":"eee.yyy" "time":"2014-10-31T15:35:30+00:00" "records":"207">,
#<CSV::Row "name":"sss.zzz" "time":"2014-10-31T15:35:44+00:00" "records":"205">,
#<CSV::Row "name":"sss.qqq" "time":"2014-10-31T15:35:59+00:00" "records":"220">,
#<CSV::Row "name":"sss.www" "time":"2014-10-31T15:36:15+00:00" "records":"220">,
#<CSV::Row "name":"eee.xxx" "time":"2014-10-31T15:36:30+00:00" "records":"99">,
#<CSV::Row "name":"eee.yyy" "time":"2014-10-31T15:36:42+00:00" "records":"210">,
#<CSV::Row "name":"sss.zzz" "time":"2014-10-31T15:36:57+00:00" "records":"225">,
#<CSV::Row "name":"sss.qqq" "time":"2014-10-31T15:37:12+00:00" "records":"210">,
#<CSV::Row "name":"sss.www" "time":"2014-10-31T15:37:25+00:00" "records":"230">]
我希望最终得到像这样的哈希:
{"eee.xxx" => [98,99],
"eee.yyy" => [207,210],
"sss.zzz" => [205,225],
"sss.qqq" => [220,210],
"sss.www" => [220,203]}
有什么想法吗?
答案 0 :(得分:1)
是的,如下所示: -
hash = array.each_with_object(Hash.new { |h,k| h[k] = [] }) do |row,hsh|
hsh[row['name']] << row['records']
end
查看方法CSV::Row#[]
和new {|hash, key| block } → new_hash
方法。
另一种方式是: -
hash = array.each_with_object({}) do |row,hsh|
(hsh[row['name']] ||= []) << row['records']
end