5
A
回答
2
這幾乎就像你輸入你的標題:
array.select {|s| s.include? "good"}
這裏的DOC:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select
2
還有這個特殊的方法:
array.grep(/good/) # => ["Ham is good"]
有了你可以做一個#grep很多,因爲它需要一個正則表達式...
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
相關問題
- 1. 查找所有不包含特定字符串的元素
- 2. GREP獲得包含特定字符串的所有字符串
- 3. 檢查字符串元素包含數組字符串
- 4. 如何選擇所有包含特定子字符串的元素?
- 5. 將包含數組元素的字符串轉換爲數組
- 6. 刪除不包含「IN」的字符串數組中的所有元素
- 7. 查找列表中包含字符串數組中的值的所有元素
- 8. 如何更改包含字符串的元素上方的類?
- 9. 刪除字符串和每個包含特定字符串的元素後的所有內容
- 10. 檢查字符串數組元素只包含元素的另一個數組
- 11. 從包含特定字符串的數組創建數組
- 12. 查找包含字符串數組中子字符串的所有字符串
- 13. 字符串包含列表中的所有元素
- 14. 所有字符串的正則表達式不包含特定的字符串
- 15. 如果包含字符串,則刪除所有元素
- 16. 刪除LINQ中不包含特定字符串的所有行
- 17. sed:如何替換包含特定字符串的所有行?
- 18. 如何搜索包含特定字符串的所有文件?
- 19. SAS:讀取包含特定字符串的所有文件
- 20. Mod重寫包含特定字符串的所有網址
- 21. 刪除名稱中包含特定字符串的所有Cookie
- 22. XSLT選擇包含特定子字符串的所有節點
- 23. 打印包含包含特定字符串的文件的所有目錄
- 24. 打印包含指定子字符串的所有字符串
- 25. 檢查字符串是否包含數組中的元素
- 26. 目標-C,排序包含字符串元素的字符串數組
- 27. 更改大字符串數組中的特定字符
- 28. 包含有特定屬性的元素計數組
- 29. 字符串方法來更改Scala中的特定元素
- 30. 如何知道一個數組只包含的所有元素的特定值
這並不能解決將數組元素設置爲其他值的問題。 – cvshepherd
@maprihoda請注意,雖然'grep' _is_方便,但沒有什麼能阻止你用'select'或'find'來使用正則表達式(就像我的答案)。事實上,你可以用塊方法做更多**,例如'select {| s | s =〜/ good/i && s.length> 3}'。 – Phrogz
@Phrogz在正則表達式方面更多;儘管如此,你是對的,你可以用select做很多事情,你的評論中的第二個選擇示例很好地說明了它 – maprihoda