Module: Enumerable
- Defined in:
- lib/data-table/enum.rb
Overview
Custom Enumerable methods
Instance Method Summary collapse
-
#each_pair_recursive ⇒ Object
Traverse a given nested hash until we reach values that are not hashes.
-
#each_pair_with_parents(limit = 0, levels = nil) ⇒ Object
Iterates recusively over a nested collection while keeping track of the ancestor groups.
-
#group_by_recursive(groupings) ⇒ Object
Use a set of provided groupings to transform a flat array of hashes into a nested hash.
Instance Method Details
#each_pair_recursive ⇒ Object
Traverse a given nested hash until we reach values that are not hashes.
23 24 25 26 27 28 29 30 31 |
# File 'lib/data-table/enum.rb', line 23 def each_pair_recursive each_pair do |k, v| if v.is_a?(Hash) v.each_pair_recursive { |i, j| yield i, j } else yield(k, v) end end end |
#each_pair_with_parents(limit = 0, levels = nil) ⇒ Object
Iterates recusively over a nested collection while keeping track of the ancestor groups.
When passing a block with a third variable the parents will be passed to the block as an array. e.g. [‘parent1’, ‘parent2’, ‘parent3’]
limit
can be passed as an optional integer to limit the depth of recursion.
levels
is internal use and is used to build the array of ancestors
44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/data-table/enum.rb', line 44 def each_pair_with_parents(limit = 0, levels = nil) levels ||= [] each_pair do |k, v| levels << k if v.is_a? Hash v.each_pair_with_parents(limit, levels) { |i, j, next_levels| yield(i, j, next_levels) } elsif v.is_a? Array levels.pop yield(k, v, levels) end end levels.pop end |
#group_by_recursive(groupings) ⇒ Object
Use a set of provided groupings to transform a flat array of hashes into a nested hash. groupings should be passed as an array of hashes. e.g. groupings = [0, 1, 2]
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/data-table/enum.rb', line 8 def group_by_recursive(groupings) groups = group_by do |row| row[groupings[0]] end if groupings.count == 1 groups else groups.merge(groups) do |_group, elements| elements.group_by_recursive(groupings.drop(1)) end end end |