首页 > 解决方案 > 替换字符串中的多个不同单词

问题描述

我在 Ruby 中有一个字符串:

The animal_name is located in the some_place 

如何animal_name用“鱼”和some_place“湖”代替

我已经使用sentence.sub! 'animal_name', 'fish'了对一个单词非常有效的方法,但我只允许使用 2 个参数,因此我不能同时更改不同类型的单词。

我想做类似的事情:

sentence.sub! ('animal_name' => 'fish', 'some_place' => 'lake')

关于如何做到这一点的任何想法?

标签: ruby

解决方案


这是因为sub!可以通过三种方式调用:

sub(pattern, replacement) → new_str
sub(pattern, hash) → new_str
sub(pattern) {|match| block } → new_str 

但是您没有使用任何这些形式。您只传递了哈希,因此您仍然需要该模式。

但是,这不会像您期望的那样工作,因为sub仅替换模式中的第一个匹配项:

来自文档:
返回 str 的副本,其中第一次出现的模式被第二个参数替换。

因此,您可以尝试使用gsub代替(或gsub!),但始终传递模式:

p 'The animal_name is located in the some_place'.gsub(/\b\w+_.*?\b/, 'animal_name' => 'fish', 'some_place' => 'lake')
# "The fish is located in the lake"

(注意,正则表达式只是一个例子。这是我能做的最好的一个例子。)


推荐阅读