Convert array of 2-element arrays into a hash, where duplicate keys append additional values

后端 未结 4 1018
感动是毒
感动是毒 2020-12-01 05:03

For example

Given an array:

array = [[:a,:b],[:a,:c],[:c,:b]]

Return the following hash:

hash = { :a => [:b,:c         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 06:03

    This can be done fairly succinctly using each_with_object.

    array.each_with_object({}) { |(k, v), h| h[k] = (h[k] || []) + [v] }
    

    Demonstrating in irb:

    irb(main):002:0> array = [[:a,:b],[:a,:c],[:c,:b]]
    => [[:a, :b], [:a, :c], [:c, :b]]
    irb(main):003:0> array.each_with_object({}) { |(k, v), h| h[k] = (h[k] || []) + [v] }
    => {:a=>[:b, :c], :c=>[:b]}
    

提交回复
热议问题