class String
def squish
x = 0
x += 1 while self[x] == 32
lines.collect { |line| line.chomp[x..-1] }.join("\n")
end
end
puts <<-EOS.squish
hi
...my friend over
there
EOS
# => hi\nmy friend over\n there\n
Refactorings
No refactoring yet !
Serguei Filimonov
February 27, 2010, February 27, 2010 16:18, permalink
Hey friend,
I think in this kinda problem, a regular expression should help. Here's what I propose (note: I haven't tested it too extensively, but seems to work on a couple of strings)
class String
def squish
indent = self[/^\s+/]
self.gsub(/^#{indent}/, '')
end
end
puts <<-EOS.squish
hi
...my friend over
there
EOS
# => hi\nmy friend over\nthere\n
steenslag
February 27, 2010, February 27, 2010 21:06, permalink
class String
def squish
strip.gsub(/\s+/, " ")
end
end
Martin Plöger
March 4, 2010, March 04, 2010 21:36, permalink
You could also use ONLY a RegEx (no need to define an 'indent' variable like Serguei did).
steenslag's and Serguei's solution do not replace the three dots '...' or did I get it wrong? Otherwise Serguei's solution is pretty fine, except that you could get rid of the temp-variable (just remove the 'length'-method-call in my example)
class String
def squish
self.gsub(/^.{#{self[/^\s+/].length}}/, '')
end
end
p <<-EOS.squish
hi
...my friend over
there
EOS
# => "hi\nmy friend over\nthere\n"
The code doesn't feel elegant enough. What other options are there (excluding the rails equivalent function).