In Ruby, I have a string of identical characters — let’s say they’re all exclamation points, as in !!!!. I would like to replace the characters at certain indices with ‘*’ if the integer corresponding to that index meets some criteria.
For example, let’s say I want to replace all the characters whose indices are even numbers and are greater than 3. In the string !!!!!!!! (8 characters long), that results in !!!!*!*! (indices 4 and 6 have been replaced).
What’s the most compact way to do this?
Here is a version that will modify an existing string in place: