Ruby:替换字符串的一部分

sup*_*iku 2 ruby regex string replace

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

string = "Hello, @name. You did @thing." # example
Run Code Online (Sandbox Code Playgroud)

基本上,我的字符串是@word动态的描述.我需要在运行时用值替换每个值.

string = "Hello, #{@name}. You did #{@thing}." # Is not an option!
Run Code Online (Sandbox Code Playgroud)

@word基本上是一个变量,但我不能使用上面的方法.我该怎么办?

Mla*_*vić 7

而是进行搜索/替换,您可以使用Kernel#sprintf方法或其%简写.结合Hashes,它可以非常方便:

'Hello, %{who}. You did %{what}' % {:who => 'Sal', :what => 'wrong'}
# => "Hello, Sal. You did wrong" 
Run Code Online (Sandbox Code Playgroud)

使用Hash而不是Array的优点是您不必担心排序,并且可以在字符串中的多个位置插入相同的值.


Cha*_*ell 6

您可以使用占位符来格式化字符串,这些占位符可以使用 String 的运算符动态切换%

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'
Run Code Online (Sandbox Code Playgroud)

可能的用例:假设您正在编写一个脚本,该脚本将名称和操作作为参数。

puts "Hello, %s. You did %s" % ARGV
Run Code Online (Sandbox Code Playgroud)

假设“tony”和“nothing”是前两个参数,您将得到'Hello, Tony. You did nothing'.