2013-03-13 135 views
2

我有以下规定的图案许多字符串:红宝石:字符串替换零件

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

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

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

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

+0

尝试搜索它 - 使用此:'[ruby]替换字符串哈希'。解决方案可以像所期望的那样简单(一到两个内联表达式)或复杂(模板库)。 – 2013-03-13 19:35:58

回答

6

代替搜索/替换,您可以使用Kernel#sprintf方法或其%速记。与散列相结合,它可以来很方便:

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

使用Hash,而不是数组的好处是,你不必担心顺序,你可以有插在多个地方相同的值字符串。

3

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

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 

假设“托尼”和“无”是前两个参数,你会得到'Hello, Tony. You did nothing'