Terser way of generating deeply nested hash
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) || {}.