SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

Unindenting text block

Posted on July 6th, 2007 by Alex Gorbatchev. In Ruby. No comments yet...

Unindenting a block of text involves finding a common minimum indent in every line and removing it. Here’s how I have done it. As with any text processing, the larger the text is, the slower it is.

def unindent_text(src)
  indents = []

  src.each_line do |line|
    indents < < $1.length if not line =~ /^\s*$/ and line =~ /^(\s+)/
  end

  indent = indents.min
  return src if indent == 0

  lines = []

  src.each_line do |line|
    lines << line.gsub(/^\s{#{indent}}/, '').gsub(/(\r\n|\n|\r)$/, '')
  end

  lines.join("\n")
end
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet, be the first one!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr