Check If Any Number in a Ruby Array Is Greater Than or Equal to 100

Given a Ruby array of [5, 20, 13, 100], how can check if any single one of those items is >= 100?

Ultimately wanting it to return true or false.

Seems I could do something like arr.select { |num| num >= 100 } and count them, but seems there'd be a more succinct method or it.

2 Answers

Try [5, 20, 13, 100].any?{|x| x >= 100 }.

8

From a basic point of view you can do with your Array ary:

a nice old plain for:

ret = false
for i in 0...(ary.size)
  if ary[i] >= 100
    ret = true
    break
  end
end

or you can use a while

ret = false
i = 0
while not ret or i < ary.size
  ret = ary[i] >= 100
  i += 1
end

or you can use an each method on the array:

ret = false
ary.each do |el|
  ret = true if el >= 100
end

or you can use any? like in @Philip answer

or you can use the max method, as cleverly suggested by @sagar-pandya (this solution is extremely nice, but requires to traverse the whole array):

ary.max >= 100

or you can map your array on a newer array of boolean (but this requires two loops over two arrays, thus it is not as efficient as other solutions), and then inject the result in a new variable with the result:

bol = ary.map { |el| el >= 100 }
ret = bol.inject { |s, el| s or el }

or you can use directly inject (but this time you have to set initial conditions):

ret = ary.inject(false) { |s, el| s or (el >= 100) }

Chose your weapon :). But if you want to do it right think about (given your specific task):

  • using a method that traverse the array only once;
  • using a method that stops when it has found a true condition.
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest