0

私のコードはここにあります

str= "In 2004, Obama received national attention during his campaign to represent Illinois in the United States Senate"
 arr =str.scan(/\S+(?:\s+\S+)?/)
 it gives
 arr=["In 2004,", "Obama received", "national attention", "during his", "campaign to", "represent Illinois", "in the", "United States", "Senate"]
   fresh_arr=[]
   arr.each do |el|
     if !arr.match(/is|am|are|this|his/)
        fresh_arr << el
     end
   end

今、私は(is、am、are、this、his)タイプの文字列を含む要素を削除したいので、次のような結果になります

arr=["Obama received", "national attention","represent Illinois","United States", "Senate"]

非常に大きなデータがあり、6 秒かかります。別の方法でこれを行うことはできますか

4

1 に答える 1

2

それを行う簡単な方法。しかし、性能についてはわかりません。mapあなたが実行しているループをまだ実行しているためです。

   arr.map{|x| x unless x =~ /\b(in|am|are|his|this)\b/i}.compact

基準:

> my_bm(500000){arr.map{|x| x unless x =~ /\b(in|am|are|his|this)\b/i}.compact}
      user     system      total        real
  7.430000   0.000000   7.430000 (  7.451064)
 => nil 

> my_bm(500000){arr.reject! { |e| e =~ /\b(in|am|are|his|this)\b/i }}
      user     system      total        real
  4.620000   0.000000   4.620000 (  4.623782)


> my_bm(5000000){arr.map{|x| x unless x =~ /\b(in|am|are|his|this)\b/i}.compact}
      user     system      total        real
 50.790000   0.010000  50.800000 ( 50.840533)

> my_bm(5000000){arr.reject! { |e| e =~ /\b(in|am|are|his|this)\b/i }}
      user     system      total        real
 46.140000   0.010000  46.150000 ( 46.198752)
 => nil 
于 2013-03-23T05:08:05.437 に答える