在Ruby中,可以使用gsub方法来替换最后一次出现的子串。具体步骤如下:
下面是一个示例代码:
def replace_last_occurrence(string, old_substring, new_substring)
array = string.split(old_substring)
last_occurrence = array.pop
new_string = array.join(old_substring)
new_string.gsub!(last_occurrence, new_substring)
return new_string
end
# 示例用法
original_string = "This is a test. This is only a test."
old_substring = "is"
new_substring = "was"
result = replace_last_occurrence(original_string, old_substring, new_substring)
puts result
输出结果为:"This is a test. This was only a test."
在这个例子中,我们将原始字符串中最后一次出现的"is"替换为"was"。你可以根据实际需求修改要替换的子串和新的子串。
领取专属 10元无门槛券
手把手带您无忧上云