Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To output to plain HTML you can just perform a recursive call of the same function within a <code>each</code> block (or use the function <em>as</em> the <code>each</code> block as I have done here):</p> <pre><code>def hash_to_html key,value if value.nil? puts "&lt;li&gt;#{key}&lt;/li&gt;" elsif value.is_a?(Hash) puts "&lt;li&gt;#{key}" puts "&lt;ul&gt;" value.each(&amp;method(:hash_to_html)) puts "&lt;/ul&gt;&lt;/li&gt;" else fail "I don't know what to do with a #{value.class}" end end puts "&lt;ul&gt;" yourhash.each(&amp;method(:hash_to_html)) puts "&lt;/ul&gt;" </code></pre> <p>To output to whatever templating language you're using (HAML, I think), we need to keep track of indentation, so things are a little more complicated -- we're going to use a function that takes the indenting depth as a parameter, and returns another function to be called on each key/value pair that prints that key/value pair (recursively) with appropriate indentation. (In functional programming, calling a function this way is called a "partially applied function", and they're usually a little easier to define than in Ruy.)</p> <pre><code>def hash_to_haml depth lambda do |key,value| puts " "*depth + "%li #{key}" if value.nil? # do nothing # (single this case out, so as not to raise an error here) elsif value.is_a?(Hash) puts " "*(depth+1) + "%ul" value.each(&amp;hash_to_haml(depth+2)) else fail "I don't know what to do with a #{value.class}" end end end puts "%ul" yourhash.each(&amp;hash_to_haml(1)) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload