Issue #5663 has been updated by Demian Ferreiro.


I found this issue looking for a single-pass alternative to `.map{...}.compact`.

The former example uses `{ |i| i + 1 if i.even? }`, which reads almost like a comprehension and has a clear separation between the condition and the transformation. But sometimes it's not so easy to achieve such separation:

~~~ruby
# Generate an array of integers from untrusted input.
['', '42', 'nope', :not_even_int_convertible].compact_map { |x| Integer(x) rescue nil } # => [42]
~~~

BTW, i think that `compact_map` sounds quite natural for what this method does, but it could also be an extension to `compact` as others have mentioned:

~~~ruby
['', '42', 'nope', :not_even_int_convertible].compact { |x| Integer(x) rescue nil } # => [42]
~~~


As long as this is considered an alternative to map + concat, i think it makes sense not to worry about the edge case of wanting to preserve the nils, as the purpose of compact is to wipe them out. For those cases a combination of `select` and `map` can be used, or `grep` with a proc as its "pattern" argument to avoid having two iterations.

----------------------------------------
Feature #5663: Combined map/select method
https://bugs.ruby-lang.org/issues/5663#change-46128

* Author: Yehuda Katz
* Status: Assigned
* Priority: Normal
* Assignee: Yukihiro Matsumoto
* Category: lib
* Target version: next minor
----------------------------------------
It is pretty common to want to map over an Enumerable, but only include the elements that match a particular filter. A common idiom is:

enum.map { |i| i + 1 if i.even? }.compact

It is of course also possible to do this with two calls:

enum.select { |i| i.even? }.map { |i| i + 1 }

Both cases are clumsy and require two iterations through the loop. I'd like to propose a combined method:

enum.map_select { |i| i + 1 if i.even? }

The only caveat is that it would be impossible to intentionally return nil here; suggestions welcome. The naming is also a strawman; feel free to propose something better.



-- 
https://bugs.ruby-lang.org/