[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) ...
?
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.
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.
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.
You could take the intersection of two arrays, and see if it's not empty:
([2, 6, 13, 99, 27] & [2, 6]).any?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With