SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

Ruby: get full history (all parents) of a hash node

Posted on September 23rd, 2007 by Alex Gorbatchev. In Ruby. 3 comments!

Nested hashes could be used to represent tree structures. Here’s a code to to find a node by key and get all of its parents:

def hash_history(hash, desired_key, &block)
  return false unless Hash === hash

  hash.each_pair do |key, value|
    if key == desired_key or hash_history(value, desired_key, &block)
      yield(key, value)
      return true
    end
  end

  return false
end

hash = {
  :level_1 => {
    :level_2 => {
      :level_3 => {
        :search => 'test'
      }
    }
  }
}

hash_history(hash, :search) { |key, value| puts key }

# prints out...
# search
# level_3
# level_2
# level_1
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 comments.

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr