dimid dimid - 6 months ago 12
Ruby Question

Replace several substrings by indices at once in ruby

It's a similar question to this one, but I'd like to replace several substrings using indices. I can't just chain replacements since the indices refer to the original string. So I ended up counting chars, but there must be a better way.

res = original_string
delta = 0
# to keep things simple, assume replacements just contains objects which have start, end indices and replacements
replacements.each do |r|
old_str = original_str[r.start_offset .. r.end_offset]
new_str = r.replacement
res[r.start_offset + delta .. r.end_offset + delta] = new_str
delta += new_str.size - old_str.size
end

Answer

Just start replacing from the end. Then the indexes are always valid:

# to keep things simple, assume replacements just contains 
# objects which have start, end indices and replacements
replacements.sort_by(&:start_offset).reverse.each do |r|
  string[r.start_offset..r.end_offset] = r.replacement      
end
Comments