module RSplit

Constants

VERSION

Public Class Methods

rsplit(str, sep = nil, limit = 0) { |reverse| ... } click to toggle source
# File lib/rsplit.rb, line 5
def rsplit(str, sep = nil, limit = 0)
  valid_encoding?(str)
  sep = $; if sep.nil?
  case sep
  when NilClass
    nil # do nothing
  when String
    valid_encoding?(sep)
    sep = sep.reverse
  else
    raise TypeError, "wrong argument type #{sep.class} (expected String)"
  end

  if block_given?
    str.reverse.split(sep, limit).reverse_each do |elem|
      yield elem.reverse
    end
    str
  else
    str.reverse.split(sep, limit).map(&:reverse).reverse
  end
end
valid_encoding?(string) click to toggle source

Avoid Bug #11387 bugs.ruby-lang.org/issues/11387

# File lib/rsplit.rb, line 32
def self.valid_encoding?(string)
  raise ArgumentError, "invalid byte sequence in #{string.encoding.name}" unless string.valid_encoding?
end

Private Instance Methods

rsplit(str, sep = nil, limit = 0) { |reverse| ... } click to toggle source
# File lib/rsplit.rb, line 5
def rsplit(str, sep = nil, limit = 0)
  valid_encoding?(str)
  sep = $; if sep.nil?
  case sep
  when NilClass
    nil # do nothing
  when String
    valid_encoding?(sep)
    sep = sep.reverse
  else
    raise TypeError, "wrong argument type #{sep.class} (expected String)"
  end

  if block_given?
    str.reverse.split(sep, limit).reverse_each do |elem|
      yield elem.reverse
    end
    str
  else
    str.reverse.split(sep, limit).map(&:reverse).reverse
  end
end