2014-11-02 55 views
2

我有一个正确的顺序字符串数组。我想这样做:用红宝石交换每个不同的字符串

text.gsub!(/my_pattern/, array[i++]) 

换言之 - 我想与阵列[0],第二个与阵列[1]等任何提示交换my_pattern的第一次出现?

+0

我想你的意思是,对于每个'I = 0,1,2 ...','的匹配i'th串是与'阵列[I]'代替。 – 2014-11-02 02:46:09

+0

是的,这很令人兴奋,我想做的事情。 – 2014-11-02 15:21:32

回答

3

String#gsub!接受可选块。块的返回值用作替换字符串。

Enumerable#each_with_index使用:

array = ['first', 'second', 'third', 'forth', 'fifth'] 
text = 'my_pattern, my_pattern, my_pattern, my_pattern' 
text.gsub!(/my_pattern/).each_with_index { |_, i| array[i] } 
# => "first, second, third, forth" 
+0

@ zenn1337,欢迎来到Stack Overflow!有些人试图回答你的问题。如果这对你有帮助,你可以通过[接受答案](http://meta.stackoverflow.com/a/5235)告诉社区,这对你最有用。 – falsetru 2014-11-02 02:18:53

+0

......是的,尽管如此,但并不急于这样做。有些海报在选择答案之前会等待几个小时,有时甚至几天,部分原因是他们不希望阻止发布额外的,可能更好的答案。 – 2014-11-02 03:53:42

1

这应该做的工作:

replacements = array.dup 
text.gsub!(/my_pattern/) { |_| replacements.shift || 'no replacements left' } 

复制的阵列array.dup第一,因为shift修改数组。如果有比该数组中的元素更多的匹配,则该模式将被替换为字符串no replacements left。如果你想保持匹配不变,如果没有留在数组中的元素,只是这样的:

text.gsub!(/my_pattern/) { |match| replacements.shift || match } 
1

方式一:

array = ['first', 'second', 'third', 'forth', 'fifth'] 
text = 'my_pattern, my_pattern, my_pattern, my_pattern' 

enum = array.to_enum 
text.gsub!(/my_pattern/) { enum.next } 
    #=> "first, second, third, forth" 
text 
    #=> "first, second, third, forth" 

Enumerator#next将引发StopIterator异常,如果调用时结束该数组已经到达(即,如果有更多的字符串要被替换,则有arr的元素)。如果您担心这种可能性,则需要在该块中包含rescue异常并进行适当处理。