Given an array:
array = [[:a,:b],[:a,:c],[:c,:b]]
Return the following hash:
hash = { :a => [:b,:c
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