MxyL MxyL - 1 year ago 147
Ruby Question

Check if an array is subset of another array in Ruby

How can I check whether one array is a subset of another array, regardless of the order of elements?

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


a1 is a subset of a2

Answer Source

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)



See it working online: ideone

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download