Skip to content

Instantly share code, notes, and snippets.

@dmitriy-kiriyenko
Last active October 12, 2017 08:52
Show Gist options
  • Save dmitriy-kiriyenko/84b56b53cd644b88781cbaa21f889502 to your computer and use it in GitHub Desktop.
Save dmitriy-kiriyenko/84b56b53cd644b88781cbaa21f889502 to your computer and use it in GitHub Desktop.
Nested hash for nested group by
def base_for_nested_group_by(x)
end
# f(0)
Hash.new # or ArgumentError
# f(1)
Hash.new {|h1, k1| h1[k1] = []}
# f(2)
Hash.new{|h1,k1| h1[k1] = Hash.new{|h2,k2| h2[k2] = []}}
# f(3)
Hash.new{|h1,k1| h1[k1] = Hash.new{|h2,k2| h2[k2] = Hash.new{|h3,k3| h3[k3] = []}}}
# ...
def base_for_nested_group_by(n)
def nested_hash_source_code(n)
raise ArgumentError.new('Give a positive integer') if n < 1
return "Hash.new {|h#{n},k#{n}|h#{n}[k#{n}] = [] }" if n == 1
"Hash.new {|h#{n},k#{n}| h#{n}[k#{n}] = #{nested_hash_source_code(n-1)} }"
end
eval nested_hash_source_code(n.to_i)
end
def base_for_nested_group_by(n)
raise ArgumentError.new('Give a positive integer') if n < 1
return Hash.new { |h, k| h[k] = [] } if n == 1
Hash.new {|h, k| h[k] = base_for_nested_group_by(n-1) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment