Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.include? multiple values

Tags:

ruby

[2, 6, 13, 99, 27].include?(2) works well for checking if the array includes one value. But what if I want to check if an array includes any one from a list of multiple values? Is there a shorter way than doing Array.include?(a) or Array.include?(b) or Array.include?(c) ...?

like image 591
Aaron Hooper Avatar asked Sep 15 '14 03:09

Aaron Hooper


People also ask

Can an array have multiple values?

An array in Java is used to store multiple values in a single variable, instead of declaring separate variables for each value. Therefore, an array is a collection of fixed elements in what can be seen as a list. Each element in an array consists of the same data type and can be retrieved and used using its index.

Can we pass array to includes?

Includes() is a simple array function which returns true if the passed value matches a value within the array. The problem with includes() is that it requires a string value and therefore you can't pass an array to it.

Does include work with array?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.


2 Answers

You could take the intersection of two arrays, and see if it's not empty:

([2, 6, 13, 99, 27] & [2, 6]).any? 
like image 103
August Avatar answered Sep 19 '22 22:09

August


You can use the Enumerable#any? method with a code block to test for inclusion of multiple values. For example, to check for either 6 or 13:

[2, 6, 13, 99, 27].any? { |i| [6, 13].include? i } 
like image 31
Todd A. Jacobs Avatar answered Sep 22 '22 22:09

Todd A. Jacobs