Created
February 17, 2016 21:53
-
-
Save vitalikdanchenko/16ef9d9d5eb9d8d5a36d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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