Sha256: ddcf34a2dbcae71e1f3b7fd38610ffd9f16eac14d27137af8b759dfd21f77e3b

Contents?: true

Size: 1.61 KB

Versions: 32

Compression:

Stored size: 1.61 KB

Contents

class String
  # http://grosser.it/2011/08/28/ruby-string-naive-split-because-split-is-to-clever/
  # "    ".split(' ') == []
  # "    ".naive_split(' ') == ['','','','']
  # "".split(' ') == []
  # "".naive_split(' ') == ['']
  def naive_split(pattern)
    pattern = /#{Regexp.escape(pattern)}/ unless pattern.is_a?(Regexp)
    result = split(pattern, -1)
    result.empty? ? [''] : result
  end

  def tabs_to_spaces!
    gsub!("\t",' ' * Ruco::TAB_SIZE)
  end

  def leading_whitespace
    match(/^\s*/)[0]
  end

  def leading_whitespace=(whitespace)
    sub!(/^\s*/, whitespace)
  end

  # stub for 1.8
  unless method_defined?(:force_encoding)
    def force_encoding(encoding)
      self
    end
  end

  unless method_defined?(:ord)
    def ord
      bytes.first
    end
  end

  def surrounded_in?(*words)
    first = words.first
    last = words.last
    slice(0,first.size) == first and slice(-last.size,last.size) == last
  end

  # https://gist.github.com/20844
  # remove middle from strings exceeding max length.
  def ellipsize(options={})
    max = options[:max] || 40
    delimiter = options[:delimiter] || "..."
    return self if self.size <= max
    remainder = max - delimiter.size
    offset = remainder / 2
    (self[0,offset + (remainder.odd? ? 1 : 0)].to_s + delimiter + self[-offset,offset].to_s)[0,max].to_s
  end unless defined? ellipsize
end

# http://grosser.it/2010/12/31/ruby-string-indexes-indices-find-all-indexes-in-a-string
class String
  def indexes(needle)
    found = []
    current_index = -1
    while current_index = index(needle, current_index+1)
      found << current_index
    end
    found
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
ruco-0.2.18 lib/ruco/core_ext/string.rb
ruco-0.2.17 lib/ruco/core_ext/string.rb
ruco-0.2.16 lib/ruco/core_ext/string.rb
ruco-0.2.15 lib/ruco/core_ext/string.rb
ruco-0.2.14 lib/ruco/core_ext/string.rb
ruco-0.2.13 lib/ruco/core_ext/string.rb
ruco-0.2.12 lib/ruco/core_ext/string.rb
ruco-0.2.11 lib/ruco/core_ext/string.rb
ruco-0.2.10 lib/ruco/core_ext/string.rb
ruco-0.2.9 lib/ruco/core_ext/string.rb
ruco-0.2.8 lib/ruco/core_ext/string.rb
ruco-0.2.7 lib/ruco/core_ext/string.rb
ruco-0.2.6 lib/ruco/core_ext/string.rb
ruco-0.2.5 lib/ruco/core_ext/string.rb
ruco-0.2.4 lib/ruco/core_ext/string.rb
ruco-0.2.3 lib/ruco/core_ext/string.rb
ruco-0.2.2 lib/ruco/core_ext/string.rb
ruco-0.2.1 lib/ruco/core_ext/string.rb
ruco-0.2.0 lib/ruco/core_ext/string.rb
ruco-0.2.0.beta12 lib/ruco/core_ext/string.rb