mokacoding

unit and acceptance testing, automation, productivity

How to check if array contains element with block in Ruby

Sometimes, you want to know if an array contains one or more elements based on a test function.

[1,2,3,4].any? { |n| n > 2 }
# => true

If you need to get the first object that matches your criteria, you can use find.

[1,2,3,4].find { |n| n > 2 }
# => 3

Want more of these posts?

Subscribe to receive new posts in your inbox.