class String

Public Instance Methods

swap(*substrings) click to toggle source
# File lib/string_swap.rb, line 4
def swap *substrings
  # there are two arguments and they are both strings
  if substrings.count == 2 && substrings.reject { |substring| substring.class == String }.empty?
    this, that = substrings
    swap_two_substrings this, that
  # all the substrings are arrays AND each array has two elements AND both of those elements are strings
  elsif substrings.reject { |substring_pair| substring_pair.class == Array && substring_pair.count == 2 && substring_pair.reject { |substring| substring.class == String }.empty? }.empty?
    substrings.each do |substring_pair|
      this, that = substring_pair
      replace(swap_two_substrings this, that)
    end
    return self
  else
    raise ArgumentError, 'only strings, or arrays of string pairs are acceptable arguments'
  end
end

Private Instance Methods

swap_two_substrings(this, that) click to toggle source
# File lib/string_swap.rb, line 21
        def swap_two_substrings this, that
  opposite = { this => that, that => this, '' => '' }
  regex = /#{Regexp.escape this}|#{Regexp.escape that}/
  matches = scan regex
  between = split regex
  padding = (between.count - matches.count).abs.times.map { '' }
  (matches + padding).zip(between).map do |match|
    match[1].to_s + opposite[match[0]]
  end.join
end