0

我需要针对外部文件传递一个字符串,该文件包含每次出现时要执行的替换列表。

替换文件将如下所示(我愿意接受有关结构的建议,它可以是 csv、yaml 等...)

"ipsum" "foobar"
"elit" ""
"sit amet" "2312"

我的 ruby​​ 代码应该这样实现:

mystring = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam quis elit augue. Nulla tempus magna nec ligula dapibus malesuada. Fusce at orci augue, sit amet suscipit sem. Suspendisse potenti."

newstring = mystring.somemagichappenshere

并且 newstring 值应该是"Lorem foobar dolor 2312, consectetur adipiscing . Aliquam quis augue. Nulla tempus magna nec ligula dapibus malesuada. Fusce at orci augue, 2312 suscipit sem. Suspendisse potenti."

我应该如何实施?

4

2 回答 2

2

使用 csv:

require 'csv'
str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam quis elit augue. Nulla tempus magna nec ligula dapibus malesuada. Fusce at orci augue, sit amet suscipit sem. Suspendisse potenti."

replacements = "ipsum,foobar
elit,
sit amet,2312"
#construct a hash from the csv:
transform_table = Hash[CSV.parse(replacements)]
#Take the keys from the hash and use them for a regular expression:
re = Regexp.union(transform_table.keys)
#Do all substituions in one go:
p str.gsub(re, transform_table)
于 2013-04-10T11:29:51.463 回答
0

这很简单

  1. 读取文件
  2. 迭代文件中的每一行,并为每个条目使用mystring.gsub!(find, replace)替换值替换
于 2013-04-10T10:49:15.363 回答