2016-03-10 64 views
-1

我有數組:有什麼辦法檢查數組是否在數組中?

a = [1,3,4,5] 
b = [1,2,3] 

有沒有檢查任何短期方式:

a.include? b 

它應該返回true作爲3是存在的。

我可以這樣做:

b.each do |bb| 
puts true if a.include? bb 
end 

但這不是用於遍歷一個大陣,以檢查它的好方法。

+1

的可能的複製[的Ruby/Rails:如何判斷一個數組包含的其他所有元素數組?](http://stackoverflow.com/questions/7387937/ruby-rails-how-to-determine-if-one-array-contains-all-elements-of-another-array) – lifetimes

回答

1

您可以檢查數組不同的是空:

a = [1, 2, 3] 
b = [1, 3, 4, 5] 

(a - b).empty? # false 
0

您可以使用Set.disjoint?

require 'set' 
Set[1, 2, 3].disjoint? Set[3, 4] # => false 
Set[1, 2, 3].disjoint? Set[4, 5] # => true 
1

一種方式做到這一點是使用Enumerable.any?

[1, 3, 4, 5].any? { |i| [1, 2, 3].include? i } 
+1

這是唯一的答案這不會迭代一個或兩個a全部被炸燬。由於OP說他們不想迭代大數組,所以這應該是被接受的答案。 –

0

如果我減去a - b和a有一些b也有的元素,那麼新的a - b具有較少數量的元素,因爲a-b返回所有元素,a具有但b沒有。我可以根據原始尺寸檢查結果。

a = [1,3,4,5] 
b = [1,2,3] 
(a - b).size < a.size 
# => true 
1

您可以使用數組路口:

a = [1,2,3,4] 
b = [2,4] 
c = [5,6] 

它提供了以下結果:

(a & b).any? 
    # true 
    (a & c).any? 
    # false 
相關問題