Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
any?()
communitycreator

What is any?() used for in an array in Ruby?

okwudili onyejiaku

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 arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["ab", "cd", "ef", "gh", "ij"]
array4 = [false, nil, ""]
array5 = []

# match elements with patterns
a = array1.any? {|number| number > 3}
b = array2.any? {|alphabet| alphabet == "yz"}
c = array4.any?
d = array5.any?

# print returned boolean values
puts a
puts b
puts c 
puts d
any?() example

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.

RELATED TAGS

array
ruby
any?()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring