Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping and selecting at the same time

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
like image 355
sawa Avatar asked Nov 19 '25 10:11

sawa


1 Answers

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.

like image 144
megas Avatar answered Nov 22 '25 00:11

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!