Module: Datadog::Core::Utils::Array

Defined in:
lib/datadog/core/utils/array.rb

Overview

Common array-related utility functions.

Class Method Summary collapse

Class Method Details

.filter_map(array, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/datadog/core/utils/array.rb', line 8

def self.filter_map(array, &block)
  if array.respond_to?(:filter_map)
    # DEV Supported since Ruby 2.7, saves an intermediate object creation
    array.filter_map(&block)
  elsif array.is_a?(Enumerator::Lazy)
    # You would think that .compact would work here, but it does not:
    # the result of .map could be an Enumerator::Lazy instance which
    # does not implement #compact on Ruby 2.5/2.6.
    array.map(&block).reject do |item|
      item.nil?
    end
  else
    array.each_with_object([]) do |item, memo|
      new_item = block.call(item)
      memo.push(new_item) unless new_item.nil?
    end
  end
end