Terser way of generating deeply nested hash I need to generate a Ruby hash that looks like this:

{ "children" =&gt; [
  { "children" =&gt; [
    { "children" =&gt; [
      { "children" =&gt; [] }
    ]}
  ]}
]}


... for an arbitrary level of nesting.  So far the best I've come up with is:

def nested_hash(levels)
  return {} if levels &lt; 1
  root = { 'children' =&gt; [] }
  children = root['children']
  (levels - 1).times { children = (children &lt;&lt; { 'children' =&gt; [] }).first['children'] }
  root
end


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

def nested_hash(levels)
  return if levels &lt;= 0
  { "children" =&gt; [ nested_hash(levels - 1) ].compact }
end


Or it could be

def nested_hash(levels)
  return nil if levels &lt;= 0
  array = nested_hash(levels - 1)
  { "children" =&gt; 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"=&gt;[
  {"children"=&gt;[
    {"children"=&gt;[]}
  ]}
]}


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) || {}.