views:

215

answers:

1

let's say i have a multidimensional hash, and in one of the subhashes i have a key=>value pair which i need to retrieve by key. how can i do it?

example hashes:

h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}

key is always :k, and i need to get "needle"

i noticed that there is no "flatten" function for hashes in ruby 1.8, but if it'd be there, i imagine i'd just do

h.flatten[:k]

i imagine i need to write a recursive function for that?

thanks

+2  A: 

You can always write your own mission-specific extension to Hash which does the dirty work for you:

class Hash
  def recursive_find_by_key(key)
    # Create a stack of hashes to search through for the needle which
    # is initially this hash
    stack = [ self ]

    # So long as there are more haystacks to search...
    while (to_search = stack.pop)
      # ...keep searching for this particular key...
      to_search.each do |k, v|
        # ...and return the corresponding value if it is found.
        return v if (k == key)

        # If this value can be recursively searched...
        if (v.respond_to?(:recursive_find_by_key))
          # ...push that on to the list of places to search.
          stack << v
        end
      end
    end
  end
end

You can use this quite simply:

h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}

puts h.recursive_find_by_key(:k).inspect
# => "needle"

h={:k=>"needle"}

puts h.recursive_find_by_key(:k).inspect
# => "needle"

puts h.recursive_find_by_key(:foo).inspect
# => nil
tadman