25ff3dfe48d3847ecf9971aab99589fb

The code doesn't feel elegant enough. What other options are there (excluding the rails equivalent function).

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 !

D0180794e9d81d80e37ff5962032dca8

Serguei Filimonov

February 27, 2010, February 27, 2010 16:18, permalink

1 rating. Login to rate!

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
D41d8cd98f00b204e9800998ecf8427e

steenslag

February 27, 2010, February 27, 2010 21:06, permalink

2 ratings. Login to rate!
class String
  def squish
    strip.gsub(/\s+/, " ")
  end
end
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

March 4, 2010, March 04, 2010 21:36, permalink

1 rating. Login to rate!

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"

Your refactoring





Format Copy from initial code

or Cancel