Issue #5663 has been updated by sawa (Tsuyoshi Sawada).


I think this proposal has been realized under the name `Enumerable#filter_map` following the duplicate proposal #15323. So it should be closed.

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

* Author: wycats (Yehuda Katz)
* Status: Assigned
* Priority: Normal
* Assignee: matz (Yukihiro Matsumoto)
----------------------------------------
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/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>