Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/sixarm_ruby_string_replace_between/string/replace_between.rb

Overview

String#replace_between

Instance Method Summary collapse

Instance Method Details

#replace_between(other_string, start_target, stop_target, offset = 0) ⇒ Object

Replace the contents and taintedness of a string subsection with the corresponding values in other_string.

The params start_target and stop_target can each be a substring or pattern regexp.

Examples:

"hello".replace_between("r", "e", "o") => "hero"

"hello".replace_between("r", /[eo]/, /[eo]/) => "hero"


20
21
22
23
24
25
26
# File 'lib/sixarm_ruby_string_replace_between/string/replace_between.rb', line 20

def replace_between(other_string, start_target, stop_target, offset = 0)
  inner_index = index_after(start_target, offset)
  return self if nil == inner_index
  stop_index = index(stop_target, inner_index)
  return self if nil == stop_index
  return slice(0...inner_index) + other_string + slice(stop_index..-1)
end