如何替换 Ruby 中的一系列字符?

问题描述 投票:0回答:2

使用 Ruby,如何替换字符串中的一系列字符?例如,给定字符串

hellothere

如果我想将索引位置 2 到 5 处的字符替换为“#”以生成字符串

he####here

我该怎么做?

ruby-on-rails ruby string replace
2个回答
5
投票

您可以获取字符串范围并通过设置最后一个索引乘以的新字符加上 1 减去第一个索引来替换它:

def replace_in_string(str, replace, start, finish)
  str[start..finish] = replace * (finish + 1 - start)
  str
end

p replace_in_string 'hellothere', '#', 2, 5
# "he####here"

0
投票

s = '你好' s[2..5] = '####'

© www.soinside.com 2019 - 2024. All rights reserved.