ManageIQ / more_core_extensions

MoreCoreExtensions are a set of core extensions beyond those provided by ActiveSupport.
MIT License
5 stars 23 forks source link

Add Array#compact_map #63

Closed bdunne closed 4 years ago

bdunne commented 6 years ago

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

Fryguy commented 6 years ago

:+1: 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 commented 5 years ago

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

Fryguy commented 5 years ago

Also a few of these rubocops are legit.

miq-bot commented 4 years ago

Checked commit https://github.com/bdunne/more_core_extensions/commit/ec36c0b51c1c7a234a18ff7e00894ce177224738 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. :star: