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