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

后端 未结 4 996
感动是毒
感动是毒 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 05:47

    This kind of operations is very common in our project, so we added to_group_h to Enumerable. We can use it like:

    [[:x, 1], [:x, 2], [:y, 3]].to_h
    # => { x: 2, y: 3 }
    
    [[:x, 1], [:x, 2], [:y, 3]].to_group_h
    # => { x: [1, 2], y: [3] }
    

    The following is the implementation of Enumerable#to_group_h:

    module Enumerable
      if method_defined?(:to_group_h)
        warn 'Enumerable#to_group_h is defined'
      else
        def to_group_h
          hash = {}
          each do |key, value|
            hash[key] ||= []
            hash[key] << value
          end
          return hash
        end
      end
    end
    

提交回复
热议问题