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 !
mxcl
March 5, 2010, March 05, 2010 17:47, permalink
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"
dreftymac.myopenid.com
March 7, 2010, March 07, 2010 14:36, permalink
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
Samuel Cochran
June 24, 2011, June 24, 2011 20:46, permalink
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
Samuel Cochran
June 24, 2011, June 24, 2011 20:47, permalink
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
Remove leading whitespace from a string without removing the relative indentation of content within the string