Ruby将密钥合并到csv字符串中 [英] Ruby merge hashes putting keys into csv string
问题描述
在Ruby中有一种聪明的方法来实现以下功能:
hash1 = {a=> 1,b=> 2,d=> 3}
hash2 = {a=> 4,b=> 5,c=> 7}
hash3 = {a=> 4,d=> 7,e=> 9}
puts带输出的hash1.csvMerge(hash2).csvMerge(hash3)
存在:
{a=> 1,4,4,
b=> 2,5,0,
c=> 0,7,0,
d=> 3,0,7,
e=> 0,0,9}
我想要做的是合并一堆Ruby散列,在实践中,我有超过一打,成为一个单一的散列,其中的值组合成一个逗号分隔的字符串。
<$ p $ {code> hashes = [hash1,hash2,hash3]
keys = hashes.inject({}){| hh,h | hh = hh.merge(h); hh} .keys#所有密钥的集合#
default_hash = keys.inject({}){| d,k | d [k] = 0; d}#所有密钥的值为0的散列#
complemented_hashes = hashes.map {| h | default_hash.merge(h)}#缺少值填入#
p哈希值[complemented_hashes.map {| h | h.to_a} .flatten(1).group_by {| k,v | ķ}。
map {| k,v | [k,v.map {| k,v | v} .join(,)]}]
Is there a clever way to achieve the following in Ruby?
hash1 = { "a" => 1, "b" => 2, "d" => 3}
hash2 = { "a" => 4, "b" => 5, "c" => 7}
hash3 = { "a" => 4, "d" => 7, "e" => 9}
puts hash1.csvMerge(hash2).csvMerge(hash3)
with the output being:
{ "a" => "1,4,4",
"b" => "2,5,0",
"c" => "0,7,0",
"d" => "3,0,7",
"e" => "0,0,9" }
What I'm trying to do is merge a bunch of Ruby hashes, in practice I have over a dozen, into a single hash where the values are combined into a comma separated string.
hashes = [hash1, hash2, hash3]
keys = hashes.inject({}){|hh, h| hh = hh.merge(h); hh}.keys # the set of all keys #
default_hash = keys.inject({}){|d, k| d[k] = 0; d} # hash with value 0 for all keys #
complemented_hashes = hashes.map{|h| default_hash.merge(h)} # missing values filled in #
p Hash[complemented_hashes.map{|h| h.to_a}.flatten(1).group_by{|k, v| k}.
map{|k, v| [k, v.map{|k, v| v}.join(",")]}]
这篇关于Ruby将密钥合并到csv字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!