Thursday, February 07, 2008

Array Subsets and Supersets

I often find myself looking to see if an array contains all elements in another array. The code looks like this:-
!array.any? {|e| !other_array.include?(e)}

A much nicer solution is to use the build-in Set#subset because it reads so much better:
set.subset?(other_set)


A Set is like an array, but stores each element only once in an unordered sequence. You can't get at a particular index - but you can still use #each. Arrays, on the other hand, can store the same thing multiple times, and in different orders. Hence, it only makes sense to talk of 'subset' or 'superset' and not 'subarray'.

Quite usefully, Enumberable defines #to_set - which is included into Array giving us:-
array.to_set.subset?(other_array.to_set)

BTW - if you're outside rails, you'll need to require 'set'.

No comments: