Sasha
Sasha

Reputation: 6466

Remove indentation from code

I'm trying to create a function that removes extraneous starting tabs from code to make it display more neatly. As in, I would like my function to turn this:

    <div>
      <div>
       <p>Blah</p>
      </div>
    </div>

into this:

<div>
  <div>
   <p>Blah</p>
  </div>
</div>

(The goal of all this is to create a Rails partial into which I can paste formatted code to be displayed in a pre tag justified to the left).

So far, I've got this, but it's erroring, and I don't know why. Never used gsub before, so I'm guessing the problem is there (though the debugging notes also point at the first "end" line):

def tab_stripped(code)
  # find number of tabs in first line
  char_array = code.split(//)
  counter = 0
  char_array.each do |c|
    counter ++ if c == "\t"
    break if c != "\t"
  end

  # delete that number of tabs from the beginning of each line
  start_tabs = ""
  counter.times do 
    start_tabs += "\t"
      end
  code.gsub!(start_tabs, '')
  code
end

Any ideas?

Upvotes: 0

Views: 154

Answers (1)

sawa
sawa

Reputation: 168081

One from my personal library (with minor modifications):

class String
  def unindent; gsub(/^#{scan(/^\s+/).min}/, "") end
end

It is more general than what you are asking for. It takes care of not just tabs, but spaces as well, and it does not adjust to the first line, but to the least indented line.

puts <<X.unindent
    <div>
      <div>
       <p>Blah</p>
      </div>
    </div>
X

gives:

<div>
  <div>
   <p>Blah</p>
  </div>
</div>

Upvotes: 4

Related Questions