Reputation: 51
I want to be able to compare two arrays of what they have in common and not show any duplicates.
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']
sample output:
walking to the park find ice cream
Upvotes: 0
Views: 81
Reputation: 2432
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"]
Regex will be slower. Here's a quick comparison between array union and using Regexp:
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)
Upvotes: 7
Reputation: 118271
I would do as :
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"
Upvotes: 1