Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that all the elements of an array satisfy a condition?

I'm using Ruby 2.4. How do I check if all elements of my array satisfy a condition? I have

cond = true
arr.each do |e|
  if e.nil? || e.to_i < 5
    cond = false
    break
   end
end

but I feel like there's a more efficient way to do this.


1 Answers

You can rewrite that as

arr.all? { |e| e.to_i >= 5 }
like image 146
Ursus Avatar answered Oct 22 '25 03:10

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!