Sha256: 0ca1ba55a90b3a1bf97a6d50e143df36a81d730a931e126713fc11b4069d99ab

Contents?: true

Size: 605 Bytes

Versions: 20

Compression:

Stored size: 605 Bytes

Contents

class String

  # Cleave a string. Break a string in two parts at
  # the nearest whitespace.
  #
  # CREDIT: Trans

  def cleave(threshold=nil, len=nil)
    l = (len || size / 2)
    t = threshold || size

    h1 = self[0...l]
    h2 = self[l..-1]

    i1 = h1.rindex(/\s/) || 0
    d1 = (i1 - l).abs

    d2 = h2.index(/\s/) || l
    i2 = d2 + l

    d1 = (i1-l).abs
    d2 = (i2-l).abs

    if [d1, d2].min > t
      i = t
    elsif d1 < d2
      i = i1
    else
      i = i2
    end

    #dup.insert(l, "\n").gsub(/^\s+|\s+$/, '')
    return self[0..i].to_s.strip, self[i+1..-1].to_s.strip
  end

end

Version data entries

20 entries across 19 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/string/cleave.rb
facets-3.1.0 lib/core/facets/string/cleave.rb
facets-3.0.0 lib/core/facets/string/cleave.rb
facets-2.9.3 lib/core/facets/string/cleave.rb
facets-2.9.2 src/core/facets/string/cleave.rb
facets-2.9.2 lib/core/facets/string/cleave.rb
facets-2.9.1 lib/core/facets/string/cleave.rb
facets-2.9.0 lib/core/facets/string/cleave.rb
facets-2.9.0.pre.2 lib/core/facets/string/cleave.rb
facets-2.9.0.pre.1 lib/core/facets/string/cleave.rb
facets-2.8.4 lib/core/facets/string/cleave.rb
facets-2.8.3 lib/core/facets/string/cleave.rb
facets-2.8.2 lib/core/facets/string/cleave.rb
facets-2.8.1 lib/core/facets/string/cleave.rb
facets-2.8.0 lib/core/facets/string/cleave.rb
facets-2.7.0 lib/core/facets/string/cleave.rb
facets-2.6.0 lib/core/facets/string/cleave.rb
facets-2.5.0 lib/core/facets/string/cleave.rb
facets-2.5.1 lib/core/facets/string/cleave.rb
facets-2.5.2 lib/core/facets/string/cleave.rb