Skip to content

Instantly share code, notes, and snippets.

@leonelgalan
Created November 7, 2017 20:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonelgalan/aa300c308b277950c4d99c932e2502f8 to your computer and use it in GitHub Desktop.
Save leonelgalan/aa300c308b277950c4d99c932e2502f8 to your computer and use it in GitHub Desktop.
Manipulate Rails' `group(args).count` result into a hash grouped by the `args.first`. See test's `INPUT` and `EXPECTED_OUTPUT`.
# https://github.com/dam13n/ruby-bury
class Hash
def bury(*args)
if args.count < 2
raise ArgumentError, '2 or more arguments required'
elsif args.count == 2
self[args[0]] = args[1]
else
arg = args.shift
self[arg] = {} unless self[arg]
self[arg].bury(*args) unless args.empty?
end
self
end
end
# Rails' group(:a, :b).count produces a hash with array keys. Sometimes, it
# would be beneficial to have a hash with the counts for :b, grouped by :a
INPUT = {
[1, :a] => 1,
[1, :b] => 2,
[2, :a] => 1,
[2, :b] => 3,
[2, :c] => 3
}.freeze
EXPECTED_OUTPUT = {
1 => { a: 1, b: 2 },
2 => { a: 1, b: 3, c: 3 }
}.freeze
require 'minitest/autorun'
class Test < Minitest::Test
def test_group_count
output = INPUT.each_with_object({}) do |(args, count), memo|
memo.bury(*args, count)
end
assert_equal EXPECTED_OUTPUT, output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment