Ruby:替换字符串的部分

Ruby:替换字符串的部分,ruby,regex,string,replace,Ruby,Regex,String,Replace,我有许多字符串遵循某种模式: string = "Hello, @name. You did @thing." # example 基本上,我的字符串是一个描述,其中@word是动态的。我需要在运行时用一个值替换每个值 string = "Hello, #{@name}. You did #{@thing}." # Is not an option! @word基本上是一个变量,但我不能使用上面的方法。 我应该怎么做呢?您可以使用方法或其%速记来代替搜索/替换。结合哈希,它可以非常方便: '

我有许多字符串遵循某种模式:

string = "Hello, @name. You did @thing." # example
基本上,我的字符串是一个描述,其中@word是动态的。我需要在运行时用一个值替换每个值

string = "Hello, #{@name}. You did #{@thing}." # Is not an option!
@word基本上是一个变量,但我不能使用上面的方法。
我应该怎么做呢?

您可以使用方法或其
%
速记来代替搜索/替换。结合哈希,它可以非常方便:

'Hello, %{who}. You did %{what}' % {:who => 'Sal', :what => 'wrong'}
# => "Hello, Sal. You did wrong" 

使用哈希而不是数组的优点是,您不必担心排序问题,并且可以在字符串的多个位置插入相同的值。

您可以使用占位符格式化字符串,占位符可以使用字符串运算符动态切换

string = "Hello, %s. You did %s"

puts string % ["Tony", "something awesome"]
puts string % ["Ronald", "nothing"]

#=> 'Hello, Tony. You did something awesome'
#=> 'Hello, Ronald. You did nothing'
可能的用例:假设您正在编写一个脚本,将名称和操作作为参数

puts "Hello, %s. You did %s" % ARGV

假设“tony”和“nothing”是前两个参数,您将得到“Hello,tony”。您什么也没做“

尝试搜索它-使用以下命令:
[ruby]替换字符串哈希值
。解决方案可以根据需要简单(一个两个内联表达式)或复杂(模板库)。