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

# => ["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:

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.

@postmodern Oops yeah I just realized, I wasn't using that offset you can pass to #match. 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"]

@postmodern That *would* nice. Especially if it took a block, too. I mean there is but that's not the same.

@postmodern "A1A2A3".to_enum(:scan, /A/).map{ Regexp.last_match }.map{ _1.pre_match + "X" + _1.
post_match }
Sign in to participate in the conversation

A Mastodon instance for Rubyists & friends