以有效的方式从数组中拒绝元素

时间:2013-03-21 09:27:05

标签: ruby-on-rails arrays

我的数组是

 arr = ["wow what", "what anice", "anice day.currently", "day.currently i", "i am", "am in", "in delhi", "delhi but", "but in", "in night", "night i", "i am", "am going", "going to", "to us"]
    arr.each do |el|
     if !el.match('in') && !el.match('is').blank?
      fresh_arr << el
     end

但是我有110k元素数组,它给了8秒,太多时间我可以用另一种方式做到这一点

THX

3 个答案:

答案 0 :(得分:3)

使用delete_if

arr.delete_if do |e|
  e.match('in') && e.match('is').blank?
end
arr

答案 1 :(得分:3)

试试这个

arr.reject { |i| i.match('in') || i.match('is').blank? }

答案 2 :(得分:0)

您可以通过执行此操作选择所需的所有元素

arr.select{|el| !el.match('in') && !el.match('is').blank?}