Hash to HTML (hash2html) in Ruby

I needed to output a Hash as a nested HTML structure. Googling didn’t find any satisfactory results, so I decided to roll my own. UL/LI tags seemed like the best choice. It was a nice exercise in recursion.

The result is a function, which outputs a nicely indented HTML. Note, however, that it’s a very basic solution. It doesn’t cope well with anything other than Strings and Numbers (unless your objects support a nice to_s method).

# Prints nested Hash as a nested <ul> and <li> tags
# - keys are wrapped in <strong> tags
# - values are wrapped in <span> tags
def HashToHTML(hash, opts = {})
  return if !hash.is_a?(Hash)

  indent_level = opts.fetch(:indent_level) { 0 }

  out = " " * indent_level + "<ul>\n"

  hash.each do |key, value|
    out += " " * (indent_level + 2) + "<li><strong>#{key}:</strong>"

    if value.is_a?(Hash)
      out += "\n" + HashToHTML(value, :indent_level => indent_level + 2) + " " * (indent_level + 2) + "</li>\n"
    else
      out += " <span>#{value}</span></li>\n"
    end
  end

  out += " " * indent_level + "</ul>\n"
end

Who knows, maybe someone somewhere finds it useful.

Update: much more concise solution by Piotr Szotkowski.

Published by

Paweł Gościcki

Ruby/Rails programmer.

2 thoughts on “Hash to HTML (hash2html) in Ruby”

Comments are closed.