Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Does array A contain all elements of array B [duplicate]

Is there any method to check if array A contains all the elements of array B?

like image 669
el_quick Avatar asked May 04 '11 22:05

el_quick


People also ask

Are arrays in Ruby homogeneous?

A Ruby array is heterogeneous in the sense that it can store multiple data types rather than just one type.

How does array work in Ruby?

An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.

What does .first do in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


2 Answers

You can try this

a.sort.uniq == b.sort.uniq

or

(a-b).empty?

And if [1,2,2] != [1,2] in your case you can:

a.group_by{|i| i} == b.group_by{|i| i}
like image 170
fl00r Avatar answered Nov 09 '22 23:11

fl00r


This should work for what you need:

(a & b) == b
like image 8
Mark Szymanski Avatar answered Nov 09 '22 23:11

Mark Szymanski