2010-06-07 19 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的速度取决于很多上你使用的具体实现),但它非常简单。目前是否适合取决于你的目标。