对于具有键收集值的每个数组项,并使用键和值数组创建新数组

时间:2014-05-12 09:07:31

标签: ruby arrays hash

我有一个像

这样的结构的数组
   linkword =  ['people','http:mysite.org/people-appears-here'],
    ['people','http:mysite.org/people-appears-here-to'],
    ['people','http:mysite.org/people-appears-here-aswell'],
    ['crayons','http:mysite.org/crayons-appears-here-to'],
    ['crayons','http:mysite.org/crayons-appears-here-aswell'],
    ['boats','http:mysite.org/boats-appears-here-aswell'],

我想创建一个数组(哈希?),如

['people' => ['http:mysite.org/people-appears-here', 'http:mysite.org/people-appears-here-to', 'http:mysite.org/people-appears-here-aswell']], 
['crayons' => ['http:mysite.org/crayons-appears-here', 'http:mysite.org/crayons-appears-here-to']], 
['boats' => ['http:mysite.org/boats-appears-here']], 

我试图弄清楚如何做以上

linkword.each_with_object(a) { |(k,v),m| 
    while a == k 
    temphash[a] << v
    end
    pp temphash
    }
    end

1 个答案:

答案 0 :(得分:0)

linkword.group_by(&:first).each_with_object({}) {|(k, v), h| h[k] = v.flatten.reject{|i| i == k } }
#=> {"people"=>["http:mysite.org/people-appears-here", "http:mysite.org/people-appears-here-to", "http:mysite.org/people-appears-here-aswell"],
#    "crayons"=>["http:mysite.org/crayons-appears-here-to", "http:mysite.org/crayons-appears-here-aswell"],
#    "boats"=>["http:mysite.org/boats-appears-here-aswell"]}