2011-12-03 97 views

回答

2

還有這個特殊的方法:

array.grep(/good/) # => ["Ham is good"] 

有了你可以做一個#grep很多,因爲它需要一個正則表達式...

+2

這並不能解決將數組元素設置爲其他值的問題。 – cvshepherd

+2

@maprihoda請注意,雖然'grep' _is_方便,但沒有什麼能阻止你用'select'或'find'來使用正則表達式(就像我的答案)。事實上,你可以用塊方法做更多**,例如'select {| s | s =〜/ good/i && s.length> 3}'。 – Phrogz

+0

@Phrogz在正則表達式方面更多;儘管如此,你是對的,你可以用select做很多事情,你的評論中的第二個選擇示例很好地說明了它 – maprihoda

13

既然沒有答案到目前爲止,指導您如何更新數組新值的字符串,這裏有一些選擇:

# Find every string matching a criteria and change them 
array.select{ |s| s.include? "good" }.each{ |s| s.replace("bad") } 

# Find every string matching a pattern and change them 
array.grep.replace("bad").each{ |s| s.replace("bad") } 

# Find the first string matching a criteria and change it 
array.find{ |s| s =~ /good/ }.replace("bad") 

然而,上述所有會改變一個字符串的所有實例。例如:

jon = Person.new "Johnny B. Goode" 
array = [ jon.name, "cat" ] 
array.find{ |s| s =~ /good/i }.replace("bad") 

p array #=> "bad" 
p jon #=> #<Person name="bad"> Uh oh... 

如果你不希望這個副作用,如果你想更換一個不同字符串數組中的字符串,而不是變化字符串本身,那麼你需要找到該項目,並更新索引:

# Find the _first_ index matching some criteria and change it 
array[ array.index{ |s| s =~ /good/ } ] = "bad" 

# Update _every_ item in the array matching some criteria  
array[i] = "bad" while i = array.index{ |s| s =~ /good/i } 

# Another way to do the above 
# Possibly more efficient for very large arrays any many items 
indices = array.map.with_index{ |s,i| s =~ /good/ ? i : nil }.compact 
indices.each{ |i| array[i] = "bad" } 

最後,最簡單和最快的大多是無擺弄指數:

# Create a new array with the new values 
new_array = array.map do |s| 
    if s =~ /good/i # matches "Good" or "good" in the string 
    "bad" 
    else 
    s 
    end 
end 

# Same thing, but shorter syntax 
new_array = array.map{ |s| s =~ /good/i ? "bad" : s } 

# Or, change the array in place to the new values 
new_array = array.map!{ |s| s =~ /good/i ? "bad" : s } 
2

map!聽起來是一個不錯的選擇。

x = ['i', 'am', 'good'] 
def change_string_to_your_liking s 
    # or whatever it is you plan to do with s 
    s.gsub('good', 'excellente!') 
end 
x.map! {|i| i =~ /good/ ? change_string_to_your_liking(i) : i} 
puts x.inspect 
+0

好的答案,但請注意,OP從未說過有關更改字符串('gsub')的任何信息,它批發。 – Phrogz

+2

@Progrog這個問題是不是很清楚應該設置什麼 – maprihoda

+0

Maprihoda是正確的。 OP說'把字符串設置成一個新的變量。對於我們所知的所有可能意味着從字符串中創建一個整數值。它可能確實需要更換,但沒有明確說明。由於含糊不清,我沒有假設變量修改的確切意圖,並提供了一種方法,其內容可以很容易地根據他的喜好進行修改。請注意方法'change_string_to_your_liking'的名稱和註釋'#或者你打算用s'做什麼。 – kikuchiyo

相關問題