Module: MoreCoreExtensions::ArrayCompactMap

Defined in:
lib/more_core_extensions/core_ext/array/compact_map.rb

Instance Method Summary collapse

Instance Method Details

#compact_mapObject

Collect non-nil results from the block. Basically [].collect { |i| … }.compact

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


6
7
8
9
10
11
12
13
14
15
# File 'lib/more_core_extensions/core_ext/array/compact_map.rb', line 6

def compact_map
  return enum_for(:compact_map) unless block_given?

  [].tap do |results|
    each do |i|
      result = yield(i)
      results << result if result
    end
  end
end