Simultaneous display and selection
Is there a good way map
and / select
or delete_if
at the same time? At the moment I am doing one of the following, but I was wondering if there is a better way. Also, I cannot use the second one if I need a fake value in 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
+3
source to share
2 answers
How about this?
new_array = some_array.inject([]) do |arr, x|
some_condition(x) ? arr << modification(x) : arr
end
Anytime I think about mapping, then select or match and then reject, etc., it usually means that I can use enumerable to get the work done.
+2
source to share