Unindenting text block
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
No comments yet, be the first one!
Leave a Reply