Find the result of an evaluation in an Enumberable
Ruby allows mapping through an array to return a transformed array based on an evaluation in the block. It also allows finding a value in an array.
Ruby unfortunately does not have a single method that allows you to do both, i.e. loop through a list and return the first transformed value that meets a truthy condition.
To achieve this, we can leverage Ruby’s lazy enumerability.
my_val = 5
arr = [->(val) { val * 3 }, ->(val) { val * 2 }, ->(val) { val * 7 }]
arr.lazy
.map { |my_proc| my_proc.call(my_val) }
.find { |proc_val| proc_val % 10 == 0 }
# => 10 (the returned value of the second element
# in the list. Element 3 is not processed.
Many thanks to Dylan Bridgman (@dylanbr) from the #ruby channel on the ZATech Slack for sharing this neat method.
Tweet