Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'ostruct'
def deep_hash_with_default(level, default)
default_value = level > 1 ? deep_hash_with_default(level - 1, default) : default
Hash.new { |hash, key| hash[key] = default_value }
end
def deep_group(collection, *keys)
result = deep_hash_with_default keys.length, []
collection.each do |item|
# ruby 2.3
# deep_keys = keys.map { |key| item.send key }
# deep_item = result.dig(deep_keys)
# ruby < 2.3
deep_item = keys.inject(result) { |deep_item, key| deep_item[item.send(key)] }
deep_item.push(item)
end
result
end
item = OpenStruct.new
item.a = 'a'
item.b = 'b'
item.c = 'c'
deep_group([item], :a, :b, :c) # => {"a"=>{"b"=>{"c"=>[#<OpenStruct a="a", b="b", c="c">]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment