我有以下規定的圖案許多字符串:紅寶石:字符串替換零件
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基本上是一個變量,但我不能使用上面的方法。 我該怎麼做?
代替搜索/替換,您可以使用Kernel#sprintf
方法或其%
速記。與散列相結合,它可以來很方便:
'Hello, %{who}. You did %{what}' % {:who => 'Sal', :what => 'wrong'}
# => "Hello, Sal. You did wrong"
使用Hash,而不是數組的好處是,你不必擔心順序,你可以有插在多個地方相同的值字符串。
您可以使用可以使用字符串的%
運算符動態切換的佔位符來格式化您的字符串。
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'
。
嘗試搜索它 - 使用此:'[ruby]替換字符串哈希'。解決方案可以像所期望的那樣簡單(一到兩個內聯表達式)或複雜(模板庫)。 – 2013-03-13 19:35:58