55502f40dc8b7c769880b10874abc9d0

Remove leading whitespace from a string without removing the relative indentation of content within the string

def dedent()
            sRaw    =   self;
            sep     =   "\n";
            aLines  =   [];
iMargin = sRaw.split(sep.to_s).map {|line|
                aLines.push(line);
                stest   = line[/^\s*[\S]/]
                if(stest != nil)
                    stest   = stest.length-1
                end
            }
            iMargin =   iMargin.find_all{|vxx| vxx;}.min;
            iMargin =   iMargin.to_i;
aLines = aLines.map{|line|
                line    =   line.to_s
                if(line.length >= iMargin)
                    line[iMargin..line.length]
                end
            }
return aLines.join("\n")
        end

Refactorings

No refactoring yet !

25ff3dfe48d3847ecf9971aab99589fb

mxcl

March 5, 2010, March 05, 2010 17:47, permalink

1 rating. Login to rate!

Could you be more clear about what you want? This ignores tabs as I can't really see how it would work seeing as you don't specify how many spaces a tab should be considered in your example code.

class String
  def dedent
    lines = split "\n"
    indent = lines.map{ |line| /^( *)/.match(line).captures.first.length }.min
    gsub /^#{' '*indent}/, ''
  end
end
s = "\
   moo
         cow
  moos".dedent

puts s == " moo\n       cow\nmoos"
55502f40dc8b7c769880b10874abc9d0

dreftymac.myopenid.com

March 7, 2010, March 07, 2010 14:36, permalink

No rating. Login to rate!

modified to handle blank lines

class String
  def dedent
    lines   =   self.split(/[\x0a\x0d]/);
    indent  =   lines.map{|line|(vxx=line[/^([\s]+)/].to_s.length;vxx==0;)? nil:vxx;}.compact.min
    self.gsub(/^#{' '*indent.to_i}/, '');
  end
end
93a69a78c59a3219aa5d26fd612fd667

Samuel Cochran

June 24, 2011, June 24, 2011 20:46, permalink

No rating. Login to rate!

A bit more ruby-ish, efficiency tuned, ignores blank lines, added redent function.

class String
  def dedent
    indent = lines.reject(&:empty?).map { |line| line.index(/\S/) }.compact.min
    gsub /^ {1,#{indent.to_i}}/, ''
  end unless method_defined? :dedent

  def redent prefix
    prefix = " " * prefix if prefix.is_a? Numeric
    dedent.gsub! /^(?=[ \t]*\S+)/, prefix
  end unless method_defined? :redent
end
93a69a78c59a3219aa5d26fd612fd667

Samuel Cochran

June 24, 2011, June 24, 2011 20:47, permalink

No rating. Login to rate!

A bit more ruby-ish, efficiency tuned, ignores blank lines, added redent function.

class String
  def dedent
    indent = lines.reject(&:empty?).map { |line| line.index(/\S/) }.compact.min
    gsub /^ {1,#{indent.to_i}}/, ''
  end unless method_defined? :dedent

  def redent prefix
    prefix = " " * prefix if prefix.is_a? Numeric
    dedent.gsub! /^(?=[ \t]*\S+)/, prefix
  end unless method_defined? :redent
end

Your refactoring





Format Copy from initial code

or Cancel