116 views
ruby each_sub, all_indexes === Via: https://ruby.social/@postmodern/108596810631099421 ```ruby class String def each_sub(pattern, replacement) all_indexes(pattern).each do |start| finish = start + match(pattern, start).match_length(0) head = self[...start] replaced = self[start...finish].sub(pattern, replacement) tail = self[finish..] yield [head, replaced, tail].join end end def all_indexes(pattern) enum_for(:scan, pattern).map { Regexp.last_match.begin(0) } end end "A1A2A3".each_sub("A", "X") do |subbed| puts subbed end # X1A2A3 # A1X2A3 # A1A2X3 ```