Manish Singh
Manish Singh

Reputation: 82

How to check if any element of an array is greater than 100?

This should return true

array = [30, 40, 50, 100]

This should return false:

array = [10, 20, 30, 40]

Does a predefined function exist?

Upvotes: 0

Views: 2712

Answers (2)

Kaka Ruto
Kaka Ruto

Reputation: 5125

I wanted to find the first number that is greater than 100 on the array. If you are here for the same, then find the answers below

[30, 40, 50, 100, 110, 120].find { |n| n > 100 }

#=> 110

And if you want to find all the numbers greater than 100

[30, 40, 50, 100, 110, 120].find_all { |n| n > 100 }

#=> [110, 120]

Upvotes: 2

Ursus
Ursus

Reputation: 30056

Use any?

[30,40,50,100].any? { |item| item >= 100 } # => true
[10,20,30,40].any? { |item| item >= 100 } # => false

Note that even in your first example none of the elements is greater than 100, I took for granted you meant greater than or equals to 100

Upvotes: 7

Related Questions