Project

General

Profile

Bug #15123

Enumerable#compact proposal

Added by printercu (Max Melentiev) 9 days ago. Updated 8 days ago.

Status:
Open
Priority:
Normal
Target version:
-
[ruby-core:89017]

Description

Hi!

While Enumerable does not provide #compact method, it requires changing code in some cases to substitute array with enumerator.

For example, to reduce memory usage it's usual to change large_array.map { to_heavy_object }.chained_methods to large_array.lazy.... However if chained_methods contains compact, this change will fail. Replacing compact with reject(&:nil?) fixes it.

What do you think about adding #compact to Enumerable?

History

#1 [ruby-core:89019] Updated by greggzst (Grzegorz Jakubiak) 9 days ago

I'm in favor of this proposal. It simplifies working with large and small collections so one doesn't have to remember that can't use #compact when enumerator is returned and have to fall back to #reject(:nil?).

#2 [ruby-core:89023] Updated by marcandre (Marc-Andre Lafortune) 9 days ago

  • Assignee set to matz (Yukihiro Matsumoto)

Proposal seems acceptable to me.

Just to be clear: I imagine that Lazy#compact would still be lazy. Also compact is roughly select(&:itself), not reject(&:nil?) which would wrongly keep false.

#3 [ruby-core:89026] Updated by Eregon (Benoit Daloze) 9 days ago

marcandre (Marc-Andre Lafortune) wrote:

Also compact is roughly select(&:itself), not reject(&:nil?) which would wrongly keep false.

No, #compact only removes nil: ["a" ,false ,nil].compact => ["a", false].

#4 [ruby-core:89029] Updated by shevegen (Robert A. Heiler) 8 days ago

I think if the meaning is consistent (e. g. .compact meaning to eliminate
nil values from a given collection) then this seems ok. Perhaps this could
be added for the next developer meeting.

#5 [ruby-core:89031] Updated by marcandre (Marc-Andre Lafortune) 8 days ago

Eregon (Benoit Daloze) wrote:

No, #compact only removes nil: ["a" ,false ,nil].compact => ["a", false].

Lol, ouch, not sure how I could be so confused when I wrote that, sorry!

Also available in: Atom PDF