Module: HashOp::Grouping

Defined in:
lib/hash_op/grouping.rb

Class Method Summary collapse

Class Method Details

.group_on_path(hashes, path) ⇒ Hash

Parameters:

  • hashes (Array)

    hashes to be grouped

  • paths (Object)

    path on which the hashes must be grouped

Returns:

  • (Hash)


11
12
13
14
15
16
17
18
# File 'lib/hash_op/grouping.rb', line 11

def group_on_path(hashes, path)
  hashes.inject({}) do |result, hash|
    value_at_path = HashOp::Deep.fetch(hash, path)
    result[value_at_path] ||= []
    result[value_at_path] << hash
    result
  end
end

.group_on_paths(hashes, paths) ⇒ Hash

Parameters:

  • hashes (Array)

    hashes to be grouped

  • paths (Array)

    paths on which the hashes must be grouped, by order of grouping (1st group-level first)

Returns:

  • (Hash)


25
26
27
28
29
30
31
32
33
# File 'lib/hash_op/grouping.rb', line 25

def group_on_paths(hashes, paths)
  return group_on_path(hashes, paths.first) if paths.length == 1

  path = paths.first
  path_groups = group_on_path(hashes, path)
  path_groups.each do |group_key, grouped_hashes|
    path_groups[group_key] = group_on_paths(grouped_hashes, paths[1..-1])
  end
end