patternrubyMinor
Terser way of generating deeply nested hash
Viewed 0 times
waydeeplyterserhashnestedgenerating
Problem
I need to generate a Ruby hash that looks like this:
... for an arbitrary level of nesting. So far the best I've come up with is:
This doesn't seem particularly terse or elegant. Can anyone offer suggestions on making this more terse or elegant?
{ "children" => [
{ "children" => [
{ "children" => [
{ "children" => [] }
]}
]}
]}... for an arbitrary level of nesting. So far the best I've come up with is:
def nested_hash(levels)
return {} if levels [] }
children = root['children']
(levels - 1).times { children = (children [] }).first['children'] }
root
endThis doesn't seem particularly terse or elegant. Can anyone offer suggestions on making this more terse or elegant?
Solution
Recursion perhaps?
Or it could be
if you prefer handling the
In either case,
Note that unlike yours, these ones will return
def nested_hash(levels)
return if levels [ nested_hash(levels - 1) ].compact }
endOr it could be
def nested_hash(levels)
return nil if levels array.nil? ? [] : [array] }
endif you prefer handling the
nil upfront, instead of removing it with compactIn either case,
nested_hash(3) will get you{"children"=>[
{"children"=>[
{"children"=>[]}
]}
]}Note that unlike yours, these ones will return
nil when levels is zero or less. So you'll want to do the {} fallback elsewhere, e.g. hsh = nested_hash(x) || {}.Code Snippets
def nested_hash(levels)
return if levels <= 0
{ "children" => [ nested_hash(levels - 1) ].compact }
enddef nested_hash(levels)
return nil if levels <= 0
array = nested_hash(levels - 1)
{ "children" => array.nil? ? [] : [array] }
end{"children"=>[
{"children"=>[
{"children"=>[]}
]}
]}Context
StackExchange Code Review Q#16090, answer score: 4
Revisions (0)
No revisions yet.