array = ["Spam is bad", "Ham is good"]
我想从数组中选择包含单词'good'的元素,并将字符串设置为新变量。我怎么能这样做?
答案 0 :(得分: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 }
答案 1 :(得分:2)
这几乎就像你输入你的标题一样:
array.select {|s| s.include? "good"}
以下是文档:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-select
答案 2 :(得分:2)
还有一种特殊的方法:
array.grep(/good/) # => ["Ham is good"]
使用#grep你可以做很多事情,因为它需要一个正则表达式......
答案 3 :(得分: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