How do I replace a range of characters in Ruby?

Viewed 1288

With Ruby, how do I replace a range of characters in a string? For instance, given teh string

hellothere

If I want to replace characters at index positions two through five inclusive with "#" to result in a string

he####here

How would I do this?

1 Answers

You could get a string range and replace it by setting the new character multiplied for the last index plus 1 less the first index:

def replace_in_string(str, replace, start, finish)
  str[start..finish] = replace * (finish + 1 - start)
  str
end

p replace_in_string 'hellothere', '#', 2, 5
# "he####here"
Related