HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Terser way of generating deeply nested hash

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
waydeeplyterserhashnestedgenerating

Problem

I need to generate a Ruby hash that looks like this:

{ "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
end


This doesn't seem particularly terse or elegant. Can anyone offer suggestions on making this more terse or elegant?

Solution

Recursion perhaps?

def nested_hash(levels)
  return if levels  [ nested_hash(levels - 1) ].compact }
end


Or it could be

def nested_hash(levels)
  return nil if levels  array.nil? ? [] : [array] }
end


if you prefer handling the nil upfront, instead of removing it with compact

In 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 }
end
def 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.