Skip to content

Instantly share code, notes, and snippets.

@Merovex
Created August 2, 2020 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Merovex/59de9bf976dd8e5f18cdb7d682b8b59e to your computer and use it in GitHub Desktop.
Save Merovex/59de9bf976dd8e5f18cdb7d682b8b59e to your computer and use it in GitHub Desktop.
Ruby Table of Contents generator for Markdown file in 6 lines
puts "\nCreating Table of Contents"
# This TOC generator assumes you don't care to include the page header
toc = "## Contents\n\n" + content.scan(/^##\s?(.*)\n/iu).flatten.map do |header|
next if header == 'Contents'
indent = " " * header.count("#")
anchor = header.downcase.gsub(/\W+/,'-').chomp('-')
"%s* [%s](#%s)\n" % [indent,header,anchor]
end.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment