2014-02-10 39 views
0

兩個數組我希望能夠以兩個數組比較他們有什麼共同點,沒有表現出任何重複。紅寶石比較他們有什麼共同的

array1 = ['1. walking to the park to find some ice cream'] 
array2 = ['2. walking to the park to find ice cream and find more ice cream'] 

輸出樣本:

walking to the park find ice cream 
+0

接受[其他](http://stackoverflow.com/a/21688883/2767755)答案,我的一個是最糟糕的一個。我會刪除這個。 –

回答

1

我會做如下:

a = '1. walking to the park to find some ice cream' 
b = '2. walking to the park to find ice cream and find more ice cream' 

match = Regexp.union(a.split(" ")) 
b.scan(match).uniq.join(" ") 
# => "walking to the park find ice cream" 
+0

接受[other](http://stackoverflow.com/a/21688883/2767755)答案,我的一個是最差的一個。我會刪除這個。 –

7
  1. 開始與兩個字符串
  2. 拆分它們二者上空間
  3. 請在他們

陣列相交
a = '1. walking to the park to find some ice cream' 
b = '2. walking to the park to find ice cream and find more ice cream' 

a1 = a.split(" ") 
b1 = b.split(" ") 

common = a1 & b1 
#=> ["walking", "to", "the", "park", "find", "ice", "cream"] 

正則表達式會慢一些。這裏的陣列工會,並使用正則表達式之間的快速比較:

require 'benchmark' 

def arr_only(a,b) 
    a1 = a.split(" ") 
    b1 = b.split(" ") 
    a1 & b1 
end 

def w_regex(a,b) 
    match = Regexp.union(a.split(" ")) 
    b.scan(match).uniq 
end 

n = 100_000 
Benchmark.bm do |x| 
    x.report("arr:") { n.times {|i| arr_only(a, b) } } 
    x.report("regex:"){ n.times {|i| w_regex(a, b) } } 
end 

#     user  system  total  real 
# arr:   1.030000 0.000000 1.030000 ( 1.031033) 
# regex:  4.970000 0.010000 4.980000 ( 4.993263)