From: Alexey Muranov Date: 2011-11-23T19:33:05+09:00 Subject: [ruby-core:41246] [ruby-trunk - Feature #5663] Combined map/select method Issue #5663 has been updated by Alexey Muranov. It seems that in full generality this method needs to accept two blocks: one for selecting and one for mapping, but this would be an unusual syntax. So how about a lazy `#selecting` first, which would store a block for selecting inside `enum`, and to make `#map` check if a block for selecting is defined, and to use it? Maybe, instead of changing `#map`, a new variant of `#map` can be created that would take lazy operations into account. (For the name, i would propose `#partial_map` or `#map_partially` ( http://en.wikipedia.org/wiki/Partial_function ), or `#map_selected`.) Then the code would look like this: enum.selecting { |i| i.even? }.map_selected { |i| i + 1 } and only one loop will be needed. I've read about gems defining lazy methods for Enumerable, but i do not remember if any of them is doing exactly this. -Alexey. ---------------------------------------- Feature #5663: Combined map/select method http://redmine.ruby-lang.org/issues/5663 Author: Yehuda Katz Status: Open Priority: Normal Assignee: Category: Target version: 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. -- http://redmine.ruby-lang.org