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.{|x| some_condition(x)}.map{|x| modification(x)}{|x| modification(x) if some_condition(x)}.compact



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)


The difference is that you don't need to put the result at the end of the block.



How about this?

new_array = some_array.inject([]) do |arr, x|
  some_condition(x) ? arr << modification(x) : arr


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.



All Articles