Ruby:替换字符串的一部分

时间:2013-03-13 19:34:03

标签: ruby regex string replace

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

string = "Hello, @name. You did @thing." # example

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

string = "Hello, #{@name}. You did #{@thing}." # Is not an option!

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

2 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分:3)

您可以使用可以使用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'

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

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

假设'tony'和'nothing'是前两个参数,你会得到'Hello, Tony. You did nothing'