Wish Ruby had a String#each_sub method that returned each string with each matching substring replaced, individually

"A1A2A3".each_sub('A','X')
# => ["X1A2A3", "A1X2A3", "A1A2X3"]

Or String#all_indexes(substring) or String#all_matches(regexp) methods to find all occurrences of a substring or regexp.

@postmodern Not that you asked someone to do it, but I got sniped: pad.nixnet.services/s/TvJNXaEb

I needed one for the other which was neat, and also I'm not great with yield, blocks, and custom enumerators so there might be something obvious here that makes this more ergonomic.

@edwardloveall Interesting hadn't thought of using scan. I noticed that String#match and String#index both accept offset arguments which allows you to while loop and advance the offset each time.

Follow

@postmodern Oops yeah I just realized, I wasn't using that offset you can pass to . I was also counting the number of matches with length, not number of characters in the match. Works now with /A\d/ => ["XA2A3", "A1XA3", "A1A2X"]

Sign in to participate in the conversation
Mastodon for Tech Folks

This Mastodon instance is for people interested in technology. Discussions aren't limited to technology, because tech folks shouldn't be limited to technology either!