ruby find object in array code example
Example 1: ruby find in array
(1..10).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..10).find { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
(1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
Example 2: ruby find object in array by attribute
# Use select to get all objects in an array that match your criteria
my_array.select { |obj| obj.attr == 'value' }
# find_all and filter (in Ruby 2.6+) are aliases for select
my_array.find_all { |obj| obj.attr == 'value' }
my_array.filter { |obj| obj.attr == 'value' }
# Use find to get the first object in an array that matches your criteria
my_array.find { |obj| obj.attr == 'value' }