Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add Array#compact_map #63

Merged
merged 1 commit into from
Dec 11, 2019
Merged

Conversation

bdunne
Copy link
Member

@bdunne bdunne commented Jul 31, 2018

Too many times I find myself enumerating over an array wanting some transformed data and no nils. So, I wind up with something like this:

[1,2,3,4,5].collect { |i| i * 2 if i.odd? }.compact
=> [2,6,10]

Instead, we can have:

[1,2,3,4,5].compact_map { |i| i * 2 if i.odd? }
=> [2,6,10]

This avoids allocating an extra array before the compact

@@ -0,0 +1,17 @@
module MoreCoreExtensions
module ArraySelectResult
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be on Enumerable instead?

@Fryguy
Copy link
Member

Fryguy commented Aug 1, 2018

👍 for the idea, but I don't like the name... What are the other methods that do this "dual" thing. Only one I can think of is .flat_map. Perhaps select_and_collect or select_and_map? Otherwise there's .each_with_object and .each_with_index, which can be .each.with_object and .each.with_index. Perhaps this might be more flexible....select.collect?

Additionally, if you have a select, you probably want a reject.

@Fryguy
Copy link
Member

Fryguy commented Jan 22, 2019

Crystal lang uses compact_map, so I suggest going with that. This also then feels analogous to flat_map.

@Fryguy
Copy link
Member

Fryguy commented Jan 24, 2019

Also a few of these rubocops are legit.

@bdunne bdunne force-pushed the array_select_result branch from 3bd9c94 to ec36c0b Compare December 3, 2019 20:54
@bdunne bdunne changed the title Add Array#select_result Add Array#compact_map Dec 3, 2019
@miq-bot
Copy link
Member

miq-bot commented Dec 3, 2019

Checked commit bdunne@ec36c0b with ruby 2.5.5, rubocop 0.69.0, haml-lint 0.20.0, and yamllint 1.10.0
3 files checked, 0 offenses detected
Everything looks fine. ⭐

@Fryguy Fryguy merged commit 37ce32e into ManageIQ:master Dec 11, 2019
@bdunne bdunne deleted the array_select_result branch December 11, 2019 23:06
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants