ruby - 替换字符串中的多个不同单词
问题描述
我在 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')
关于如何做到这一点的任何想法?
解决方案
这是因为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"
(注意,正则表达式只是一个例子。这是我能做的最好的一个例子。)
推荐阅读
- python - 使用 PyDev 在 Eclipse 上导入 numpy 时出错
- python - 如何从elasticsearch django返回的查询集中获取数据
- assembly - 当立即打印 mips 中算术运算的结果时,将其直接存储到 $a0 更好吗?
- android - Volley 未在 RecyclerView 中显示数据
- javascript - Json 项目优先级
- sql - 在 SQL 中获取用户当天的最新记录
- python - 是否可以在子图中控制 xlabel 步进标签?
- javascript - 将 magento 2.1.6 升级到 2.2.7 后需要 Js 错误
- javascript - MomentJS 解析大数据字符串
- scala - Azure Databricks Notebook 在包中时无法找到“dbutils”