Report abuse


			
  def split(pattern = $FIELD_SEPARATOR, limit = nil)
    return [] if self.empty?
    return [self] if limit == 1
    matches = []

    limit = nil if limit == 0
    pattern = $FIELD_SEPARATOR if pattern.nil?
    pattern = ' ' if pattern.nil?
    
    if pattern == ' ' then
      str = self.lstrip
      pattern = %r/[\v\s]+/
    else
      str = self
      pattern = Regexp.new Regexp.quote(pattern) unless Regexp === pattern
    end

    count = 0
    skip = nil

    while match = pattern.match(str) do
      count += 1

      if match.pre_match.empty? and (match[0].nil? or match[0].empty?) then
        if skip then
          matches << skip
        else
          skip = str[0..0]
          str = str[1..-1]
          next if skip
        end
      else
        matches << "#{skip}#{match.pre_match}"
        str = match.post_match
      end

      skip = nil

      if limit and limit > 0 and count == limit then
        matches[-1] += match[0] + match.post_match
        break
      end

      matches.push *match.captures.compact
    end

    matches << str unless limit and (1..count) === limit

    unless limit then
      #p matches unless caller.join(' ') =~ /backtrace/
      matches.pop while matches.last.nil? or matches.last.empty?
    end

    return matches
  end