I want to replace the last occurrence of a substring in Ruby. What\'s the easiest way? For example, in abc123abc123, I want to replace the last abc
string = "abc123abc123" pattern = /abc/ replacement = "ABC" matches = string.scan(pattern).length index = 0 string.gsub(pattern) do |match| index += 1 index == matches ? replacement : match end #=> abc123ABC123