Project

General

Profile

Actions

Feature #17153

closed

Add Enumerable#compact_map

Added by jnchito (Junichi Ito) over 3 years ago. Updated over 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:99928]

Description

I often write code like this (map, then compact):

nums = [1, 2, 3, 4, 5]
nums.map { |n| n * 10 if n.even? }.compact
#=> [20, 40]

Or like this:

nums.select(&:even?).map { |n| n * 10 }
#=> [20, 40]

I think it would be very useful and simpler if we could do it by calling one method:

nums.compact_map { |n| n * 10 if n.even? }
#=> [20, 40]

How about introducing Enumerable#compact_map ?

Updated by sawa (Tsuyoshi Sawada) over 3 years ago

Hi Ito-san,

This is a duplicate of https://bugs.ruby-lang.org/issues/5663 and https://bugs.ruby-lang.org/issues/15323, and has been realized as Enumerable#filter_map since Ruby 2.7.0.

[1, 2, 3, 4, 5].filter_map { |n| n * 10 if n.even? }
#=> [20, 40]

Updated by jnchito (Junichi Ito) over 3 years ago

Oops! I didn't notice that. Thank you for letting me know. Please close this.

sawa (Tsuyoshi Sawada) wrote in #note-1:

Hi Ito-san,

This is a duplicate of https://bugs.ruby-lang.org/issues/5663 and https://bugs.ruby-lang.org/issues/15323, and has been realized as Enumerable#filter_map since Ruby 2.7.0.

[1, 2, 3, 4, 5].filter_map { |n| n * 10 if n.even? }
#=> [20, 40]
Actions #3

Updated by jeremyevans0 (Jeremy Evans) over 3 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0