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


Almost the same for reduction or injection

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 the result at the end of the block.

+2


source


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







All Articles