5

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?

0

2 Answers 2

5

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"
3
  • Soudns like a good idea ... how exactly would I add it to the String class?
    – user7055375
    Nov 20, 2017 at 3:23
  • 1
    @Natalia Note that just because you can, doesn't mean you should. Adding methods to core classes is strongly discouraged.
    – user229044
    Nov 20, 2017 at 3:27
  • @SebastianPalma, thanks for the edit. What is the project path I shoudl use for adding to the String clsas (e.g. lib/string.rb or something like that?)
    – user7055375
    Nov 20, 2017 at 3:31
0

You can assign the characters directly into a slice of the string like this:

s = 'hellothere'      # Initial string
s[2..5] = '####'      # Assign desired string to the desired Range 2..5
1
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Mar 16 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.