Class: HArray
Instance Method Summary collapse
- #count_by ⇒ Object
- #hashes ⇒ Object
- #merge(*groups, key:, join: :inner) ⇒ Object
- #rename_keys(**renames) ⇒ Object
- #uniq_keys ⇒ Object
Methods inherited from Array
Instance Method Details
#count_by ⇒ Object
6 7 8 9 10 11 |
# File 'lib/trials/utils/h_array.rb', line 6 def count_by hashes .group_by { |x| yield(x) } .map { |k, v| [k, v.length] } .to_h end |
#hashes ⇒ Object
2 3 4 |
# File 'lib/trials/utils/h_array.rb', line 2 def hashes self end |
#merge(*groups, key:, join: :inner) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/trials/utils/h_array.rb', line 27 def merge(*groups, key:, join: :inner) groups = [self, *groups].map do |group| group .map { |h| [h.dig(key), h] } .to_h end keys = begin case join when :inner groups.map(&:keys).reduce(&:&) when :all groups.flat_map(&:keys).uniq when :first groups.first.keys end end keys.map do |key| groups .map { |g| g.dig(key) } .compact .reduce(&:merge) end end |
#rename_keys(**renames) ⇒ Object
13 14 15 16 17 18 19 20 21 |
# File 'lib/trials/utils/h_array.rb', line 13 def rename_keys(**renames) renames.each do |orig_key, new_key| hashes.map do |h| new_h = h.dup new_h[new_key] = new_h.delete(orig_key) new_h end end end |
#uniq_keys ⇒ Object
23 24 25 |
# File 'lib/trials/utils/h_array.rb', line 23 def uniq_keys hashes.flat_map(&:keys).uniq.compact end |