Method: String#fold

Defined in:
lib/core/facets/string/fold.rb

#fold(ignore_indented = false) ⇒ Object

Returns a new string with all new lines removed from adjacent lines of text.

s = "This is\na test.\n\nIt clumps\nlines of text."
s.fold

produces

"This is a test.\n\nIt clumps lines of text. "

TODO: One arguable flaw with this that might need a fix: if the given string ends in a newline, it is replaced with a single space.

CREDIT: Trans



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/core/facets/string/fold.rb', line 19

def fold(ignore_indented=false)
  ns = ''
  i = 0
  self.scan(/(\n\s*\n|\Z)/m) do |m|
    b = $~.begin(1)
    e = $~.end(1)
    nl = $&
    tx = slice(i...b)
    if ignore_indented and slice(i...b) =~ /^[ ]+/
      ns << tx
    else
      ns << tx.gsub(/[ ]*\n+/,' ')
    end
    ns << nl
    i = e
  end
  ns
end