2010-06-07 38 views
0

我的目標是讓x這樣x("? world. what ? you say...", ['hello', 'do'])返回"hello world. what do you say..."更多的紅寶石方式gsub陣列

我有一些作品,但是從「紅寶石路」似乎遠:

def x(str, arr, rep='?') 
    i = 0 
    query.gsub(rep) { i+=1; arr[i-1] } 
end 

是否有這樣做的更地道的方式? (當然,讓我注意速度是最重要的因素。)

回答

5

如果你在談論實現函數目標的ruby方法,我只會使用"%s world" % ['hello']

如果您只是詢問實施情況,對我來說看起來很好。如果你不介意破壞陣列,你可以稍微做

query.gsub(rep) { arr.shift } 
+0

首先克隆數組將解決數組銷燬問題,如果這是個問題。 – Chuck 2010-06-07 21:44:50

2

如果有可能收緊它在你的用例,我不會添加替換字符作爲paramater,然後使用標準ruby字符串格式化機制來格式化字符串。這可以更好地控制要在字符串中替換的變量。

def x(string, values, rep='%s') 
    if rep != '%s' 
    string.gsub!(rep, '%s') 
    end 
    string % values 
end 

a = %w[hello do 12] 

puts x("? world what ? you say ?", a, '?') 
puts x("%s world what %s you say %3.2f", a) 
puts x("%s world what %s you say %3.2f", a, '%s') 

而從這個輸出是如下

 
hello world what do you say 12 
hello world what do you say 12.00 
hello world what do you say 12.00 

你將需要以此爲參數太少小心會導致異常,所以你可能希望捕獲異常,行爲得體。不知道你的用例,很難判斷這是否合適。

+0

非常感謝 - mckeed碰巧更好地適應了我的情況,但您的解決方案是我很高興知道的未來。 – 2010-06-08 01:41:51

2

較短的版本:

def x(str, *vals) str.gsub('?', '%s') % vals end 

puts x("? world what ? you say ?", 'hello', 'do', '12') 
puts x("%s world what %s you say %3.2f", 'hello', 'do', '12') 
puts x("%s world what %s you say %3.2f", 'hello', 'do', '12') 

輸出:

hello world what do you say 12 
hello world what do you say 12.00 
hello world what do you say 12.00 
+0

謝謝 - 這是如何去的好指針。 – 2010-06-08 01:42:19

1

IMO,最地道和可讀的方式是這樣的:

def x(str, arr, rep='?') 
    arr.inject(str) {|memo, i| memo.sub(rep, i)} 
end 

它可能不會有最好的性能(或者它可能非常快 - Ruby的速度取決於很多上你使用的具體實現),但它非常簡單。目前是否適合取決於你的目標。