MxyL MxyL - 6 months ago 19
Ruby Question

Check if collection is subset of another collection

Which data structure should I be using if I want to determine whether one collection is a subset of another collection?

a1 = [3, 6, 4]
a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

...?

a1 is a subset of a2

Answer

Use sets. Then you can use set.subset?. Example:

require 'set'

a1 = Set[3,6,4]
a2 = Set[1,2,3,4,5,6,7,8,9]

puts a1.subset?(a2)

Output:

true

See it working online: ideone