Answers for "find nested key in ruby hash"

1

find a key in nested hash ruby

def nested_hash_value(obj,key)
  if obj.respond_to?(:key?) && obj.key?(key)
    obj[key]
  elsif obj.respond_to?(:each)
    r = nil
    obj.find{ |*a| r=nested_hash_value(a.last,key) }
    r
  end
end

h = { foo:[1,2,[3,4],{a:{bar:42}}] }
p nested_hash_value(h,:bar)
#=> 42
Posted by: Guest on December-13-2020
0

ruby create nested hash from array

h = array.reverse.inject(value) { |a, n| { n => a } }
Posted by: Guest on February-01-2021

Code answers related to "find nested key in ruby hash"

Browse Popular Code Answers by Language