Replacing characters in Ruby string according to some rule

Posted by Kyle Kaitan on Stack Overflow See other posts from Stack Overflow or by Kyle Kaitan
Published on 2009-11-19T13:43:47Z Indexed on 2010/05/23 14:11 UTC
Read the original article Hit count: 142

Filed under:

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?

© Stack Overflow or respective owner

Related posts about ruby