<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: recursive code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Mon, 06 Oct 2008 06:15:17 GMT</pubDate>
    <description>DZone Snippets: recursive code</description>
    <item>
      <title>Find every path and it's value in a Hash</title>
      <link>http://snippets.dzone.com/posts/show/3565</link>
      <description>Extends Hash class with each_path method.&lt;br /&gt;&lt;br /&gt;This method takes a block as argument which is called each time a the recursivly searched Hash returns a key that does not point to another Hash.&lt;br /&gt;&lt;br /&gt;Example:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;paths = []&lt;br /&gt;complex_hash = Hash[&lt;br /&gt;  :a =&gt; { :aa =&gt; '1', :ab =&gt; '2' },&lt;br /&gt;  :b =&gt; { :ba =&gt; '3', :bb =&gt; '4' }&lt;br /&gt;]&lt;br /&gt;complex_hash.each_path { |path, value| paths &lt;&lt; [ path, value ] }&lt;br /&gt;paths.inspect&lt;br /&gt;# =&gt; "[[\"b/ba/\", \"3\"], [\"b/bb/\", \"4\"], [\"a/aa/\", \"1\"], [\"a/ab/\", \"2\"]]"&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Hash&lt;br /&gt;  def each_path&lt;br /&gt;    raise ArgumentError unless block_given?&lt;br /&gt;    self.class.each_path( self ) { |path, object| yield path, object }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  protected&lt;br /&gt;  def self.each_path( object, path = '', &amp;block )&lt;br /&gt;    if object.is_a?( Hash ) then object.each do |key, value|&lt;br /&gt;        self.each_path value, "#{ path }#{ key }/", &amp;block&lt;br /&gt;      end&lt;br /&gt;    else yield path, object&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 22 Feb 2007 14:54:41 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3565</guid>
      <author>boof (Florian A&#223;mann)</author>
    </item>
  </channel>
</rss>
