Skip to content

Instantly share code, notes, and snippets.

@edbond
Created August 7, 2012 14:07
Show Gist options
  • Select an option

  • Save edbond/3285643 to your computer and use it in GitHub Desktop.

Select an option

Save edbond/3285643 to your computer and use it in GitHub Desktop.
Headers
require 'pp'
h = [1, 2, 3, 1, 2, 3, 2, 1, 3, 2, 1]
opened = []
r = h.inject("") do |a, x|
# close tags if needed
while opened.last != nil && opened.last >= x
a << "</h#{opened.pop}>"
end
# open tag
a << "<h#{x}>"
# and push to opened stack
opened << x
pp opened
a
end
# close left tags
r << opened.map{|t| "</h#{t}>"}.join
pp r
[1]
[1, 2]
[1, 2, 3]
[1]
[1, 2]
[1, 2, 3]
[1, 2]
[1]
[1, 3]
[1, 2]
[1]
"<h1><h2><h3></h3></h2></h1><h1><h2><h3></h3></h2><h2></h2></h1><h1><h3></h3><h2></h2></h1><h1></h1>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment