Sha256: bf58c8be5294b4ddfe59dd6e0a0ee3dcac7aefc090a916da992aee7c676fea3a

Contents?: true

Size: 1.72 KB

Versions: 10

Compression:

Stored size: 1.72 KB

Contents

# TITLE:
#
#   String Range Extension
#
# SUMMARY:
#
#   Extensions to string for localing ranges of substrings.
#
# CREDIT:
#
#   - Thomas Sawyer

#
class String

  # Like #index but returns a Range.
  #
  #   "This is a test!".range('test')  #=> 10..13
  #
  def range(s, offset=0)
    if index(s, offset)
      return ($~.begin(0))..($~.end(0)-1)
    end
    nil
  end

  # Like #index_all but returns an array of Ranges.
  #
  #   "abc123abc123".range_all('abc')  #=> [0..2, 6..8]
  #
  #--
  # Note: should add offset ?
  #++
  def range_all(s, reuse=false)
    r = []; i = 0
    while i < self.length
      rng = range(s, i)
      if rng
        r << rng
        i += reuse ? 1 : rng.end + 1
      else
        break
      end
    end
    r.uniq
  end

  # Returns an array of ranges mapping
  # the characters per line.
  #
  #   "this\nis\na\ntest".range_of_line
  #   #=> [0..4, 5..7, 8..9, 10..13]
  #
  def range_of_line
    offset=0; charmap = []
    self.each do |line|
      charmap << (offset..(offset + line.length - 1))
      offset += line.length
    end
    charmap
  end
end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestStringRange < Test::Unit::TestCase

    def test_range
      assert_equal( (1..3), "a123a567a9".range(/123/) )
      assert_equal( (0..0), "a123a567a9".range(/a/) )
    end

    def test_range_all
      assert_equal( [ (1..3), (5..7) ], "a123a123a9".range_all(/123/) )
      assert_equal( [ (0..0), (4..4), (8..8) ], "a123a567a9".range_all(/a/) )
    end

    def test_range_of_line
      a = "0123\n456\n78"
      ltcm = a.range_of_line
      assert_equal( [0..4, 5..8, 9..10], ltcm )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.0 lib/core/facets/string/range.rb
facets-2.0.1 lib/core/facets/string/range.rb
facets-2.0.2 lib/core/facets/string/range.rb
facets-2.0.4 lib/core/facets/string/range.rb
facets-2.1.0 lib/core/facets/string/range.rb
facets-2.0.5 lib/core/facets/string/range.rb
facets-2.0.3 lib/core/facets/string/range.rb
facets-2.1.1 lib/core/facets/string/range.rb
facets-2.1.2 lib/core/facets/string/range.rb
facets-2.1.3 lib/core/facets/string/range.rb