Search code examples
ruby-on-railsrubystringreplace

How do I replace a range of characters in Ruby?


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?


Solution

  • 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"