Iterate through array, for each item with key collect value and make new array with key and array of

来源:互联网 发布:衡水星河网络 编辑:程序博客网 时间:2024/04/29 16:31
 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']]

And I want to create an array(hash?) like

#=> {"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"]} 


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"]} 

0 0