ruby-on-rails - 更改包含特定字符串的所有数组元素

标签 ruby-on-rails ruby ruby-on-rails-3

array = ["Spam is bad", "Ham is good"]

我想从数组中选择包含单词“good”的元素,并将字符串设置为新变量。我怎么能这样做?

最佳答案

由于目前为止这两个答案都没有指导您如何将数组中的字符串更新为新值,因此这里有一些选项:

# 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 }

关于ruby-on-rails - 更改包含特定字符串的所有数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368057/

相关文章:

__END__ 之后的 Ruby 数据范围

ruby - 如何在 LIKE 与 Datamapper 之间建立 OR 条件?

ruby - Ruby 中重做和重试语句的目的是什么?

ruby-on-rails-3 - ActiveRecord 查询对我的小脑袋来说太难了

ruby-on-rails - MiniProfiler 列出的额外查询

ruby-on-rails - 显示 i18n 的 Rails t 函数

ruby-on-rails - 事件管理员日期过滤器日期格式自定义

ruby-on-rails - 检测设计 session 何时过期

html - Rails,collection_check_boxes,最大选择

ruby-on-rails - Sunspot Solr 连接被拒绝