Ruby - 用另一个字符串替换第一次出现的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7963394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby - replace the first occurrence of a substring with another string
提问by Sayuj
a = "foobarfoobarhmm"
a = "foobarfoobarhmm"
I want the output as `"fooBARfoobarhmm"
我希望输出为“fooBARfoobarhmm”
ie only the first occurrence of "bar" should be replaced with "BAR".
即只有第一次出现的“bar”应该被替换为“BAR”。
回答by Yossi
Use #sub:
使用#sub:
a.sub('bar', "BAR")
回答by tbuehlmann
String#subis what you need, as Yossi already said. But I'd use a Regexp instead, since it's faster:
String#sub正如 Yossi 已经说过的那样,这就是您所需要的。但我会改用正则表达式,因为它更快:
a = 'foobarfoobarhmm'
output = a.sub(/foo/, 'BAR')
回答by Nafaa Boutefer
to replace the first occurrence, just do this:
要替换第一次出现,只需执行以下操作:
str = "Hello World"
str['Hello'] = 'Goodbye'
# the result is 'Goodbye World'
you can even use regular expressions:
你甚至可以使用正则表达式:
str = "I have 20 dollars"
str[/\d+/] = 500.to_s
# will give 'I have 500 dollars'

