Re: Ruby Quiz - Challenge #6 - Build the Table of Contents (ToC) for Documents in Markdown

Gerald Bauer <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAAxEZd8acr3Qa_yUg8bM2ZEUO2+vGE1fSH1mo1D3Ja-u5h-_ig@mail.gmail.com>
Hello,

   Wow. Thanks for the great table of contents (toc) parser / builder
script for markdown documents
and for keeping the Ruby Quiz going with your code challenge entries.

    By the way, here's my little humble test script for the table of
contents (toc):



require 'pp'

txt = File.read( './pages/meetups.md' )


HEADING_RX = /^
              \s*
              (?<level>\#+)
              \s*
              (?<title>.*?)
              \s*
              $/x


def toc( txt )

  headings = []

  stack = []
  parent = nil

  txt.each_line do |line|
    line = line.chomp( '' )

    pp line
    if (m=HEADING_RX.match(line))

      level = m[:level].size
      level_str = m[:level]
      title = m[:title]

      puts "  level: (#{level}) >#{level_str}<"
      puts "  title: >#{title}<"

      item = [level,title]

      if stack.empty?  # root - let's start
         headings << item
         stack.push( headings )
         parent = item
      else
        parent_level = parent[0]
        level_diff = level - parent_level
        if level_diff > 0
          ## up
          puts "  up +#{level_diff}"
        elsif level_diff < 0
          ## down
          puts "  down #{level_diff}"
          level_diff.abs.times { stack.pop }
          parent = stack.pop
        else
          ## same level
          parent = stack.pop
        end
        parent[2] ||= []
        parent[2] << item
        stack.push( parent )
        parent = item
      end
    end
  end

  headings
end


pp toc( txt )


  Keep it up. Cheers. Prost.

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.