Shpigford
Shpigford

Reputation: 25338

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.

Upvotes: 1

Views: 4604

Answers (2)

Matteo Ragni
Matteo Ragni

Reputation: 2956

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.

Upvotes: 0

Phlip
Phlip

Reputation: 5343

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

Upvotes: 9

Related Questions