Is there a good way to map and (select or delete_if) at the same time? At the moment, I do either of the following, but was wondering if there is a better way. Also, I cannot use the second one if I want a falsy value within the resulting array.
some_array.select{|x| some_condition(x)}.map{|x| modification(x)}
some_array.map{|x| modification(x) if some_condition(x)}.compact
Almost the same to reduce or inject
new_array = some_array.each_with_object([]) do |m,res|
res << modification(x) if some_condition(x)
end
The difference is that you don't need to put result at the end of block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With