我想查看一個數組是否包含另一個數組的每個元素。另外我想解釋重複。例如:比較包含重複項的數組元素
array = [1, 2, 3, 3, "abc", "de", "f"]
數組包含[1,2,3,3]但不包含[2,2, 「ABC」] - 太多2的
我曾嘗試以下,但顯然沒有按沒有考慮到這些騙局。
other_arrays.each { |i| array.include? i }
我想查看一個數組是否包含另一個數組的每個元素。另外我想解釋重複。例如:比較包含重複項的數組元素
array = [1, 2, 3, 3, "abc", "de", "f"]
數組包含[1,2,3,3]但不包含[2,2, 「ABC」] - 太多2的
我曾嘗試以下,但顯然沒有按沒有考慮到這些騙局。
other_arrays.each { |i| array.include? i }
此方法在兩個數組上迭代一次。 對於每個數組,它會創建一個包含每個元素出現次數的散列。
然後檢查對於subset
中的每個唯一元素,在superset
中至少有這麼多元素。
class Array
def count_by
each_with_object(Hash.new(0)) { |e, h| h[e] += 1 }
end
def subset_of?(superset)
superset_counts = superset.count_by
count_by.all? { |k, count| superset_counts[k] >= count }
end
end
[1, 2, 3, 3, "abc", "de", "f"].count_by
#=> {1=>1, 2=>1, 3=>2, "abc"=>1, "de"=>1, "f"=>1}
[1, 2, 3, 3].count_by
#=> {1=>1, 2=>1, 3=>2}
[1, 2, 3, 3].subset_of? [1, 2, 3, 3, "abc", "de", "f"]
#=> true
[2, 2, "abc"].subset_of? [1, 2, 3, 3, "abc", "de", "f"]
#=> false
如果你不想修補Array
類,你可以定義:
count_by(array)
和subset_of?(array1, array2)
。
你可以首先爲類Array
創建有用的實例方法:
class Array
def difference(other)
h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
然後陣列a
的所有元素都包含在陣列b
如果下列方法返回true
。
例如,
subarray? [1,2,3], [1,4,"cat",3,2]
#=> true
subarray? [1,2,3], [1,4,"cat",3,5]
#=> false
我發現Array#difference
具有這樣廣泛應用,我proposed它被添加到紅寶石芯。有關該方法及其用法的詳細信息可以在鏈接中找到,也可以在我對this SO問題的回答中找到。
同樣使用.all?方法'other_arrays.all? {| X | array.include? x}' –