What is any?() used for in an array in Ruby?
any?() is a built-in method in Ruby that returns a boolean value if any of the given conditions satisfies it, otherwise it returns false. Each element of the array is passed to the given block.
When a pattern is passed, the method returns true or false depending on if pattern == element.
Syntax
array.any?{block}
## OR
array.any?(pattern)
Parameters
block: This is an enumerable block where elements of the array are passed to match a pattern.
pattern: The element/pattern we want to match.
Return Value
The boolean value true is returned if the element matched the pattern, otherwise false is returned.
Code Example
In the example below, we created some arrays and checked for a pattern using the any?() method.
# create differemt arraysarray1 = [1, 2, 3, 4, 5]array2 = ["ab", "cd", "ef", "gh", "ij"]array4 = [false, nil, ""]array5 = []# match elements with patternsa = array1.any? {|number| number > 3}b = array2.any? {|alphabet| alphabet == "yz"}c = array4.any?d = array5.any?# print returned boolean valuesputs aputs bputs cputs d
Explanation
Line 14 returns true because at least one element is greater than 3.
Line 15 returns false because none of the elements of array2 is yz.
Line 16 returns true because not all elements in the array evaluate to nothing except "".
Line 17 returns false because there is no element present in the array, hence nothing to match.