Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash tree depth Ruby

Tags:

ruby

I'm supposed to write a method that takes a nested hash as input and returns that hash with added "depth" keys. So, for example, the following input:

tree = { 
  a: 1,
  b: 2, 
  c: { d: { e: 3 } }
}

would yield the following return value:

{
  a: 1,
  b: 2,
  c: {
    d: {
      e: 3,
      depth: 2
    },
    depth: 1
  },
  depth: 0
}

If the input is not a hash, then the function should return nil.

This is what I came up with:

def depth(hash)
num = 0
hash.each do |key, value|
    if value.class == Hash
    num += 1
     v[:depth] = num
    value.each do |k, v|
         if v.class == Hash
         num += 1
         v[:depth] = num
         v.each do |ky, val|
             if val.class == Hash
             num += 1
             v[:depth] = num
             val.each do |ke, vl|
                 if vl.class == Hash
                 num += 1
                v[:depth] = num
                 end
               end
             end
           end
         end
       end
    end
    num = 0
   end
end

but it's limited to hash depth of 4, and I can't just keep making the method bigger.

like image 331
Anonymous Avatar asked Jul 23 '26 08:07

Anonymous


1 Answers

Try this.

def depth(h, i=0)
  h.each_with_object(depth: i) { |(k,v),g| g[k] = v.is_a?(Hash) ? depth(v, i+1) : v }
end
depth { a: 1, b: 2, c: { d: { e: 3 } }
  #=> {:depth=>0, :a=>1, :b=>2, :c=>{:depth=>1, :d=>{:depth=>2, :e=>3}}}
like image 94
Cary Swoveland Avatar answered Jul 26 '26 02:07

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!