Module: Enumerable

Defined in:
lib/everythingrb/core/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#join_map(join_with = "", with_index: false) {|element, index| ... } ⇒ String

Combines filter_map and join operations

Examples:

Without index

[1, 2, nil, 3].join_map(" ") { |n| n&.to_s if n&.odd? }
# => "1 3"

With index

["a", "b", "c"].join_map(", ", with_index: true) { |char, i| "#{i}:#{char}" }
# => "0:a, 1:b, 2:c"

Default behavior without block

[1, 2, nil, 3].join_map(", ")
# => "1, 2, 3"

Parameters:

  • join_with (String) (defaults to: "")

    The delimiter to join elements with (defaults to empty string)

  • with_index (Boolean) (defaults to: false)

    Whether to include the index in the block (defaults to false)

Yields:

  • (element, index)

    Block that filters and transforms array elements

Yield Parameters:

  • element (Object)

    The current element

  • index (Integer)

    The index of the current element (only if with_index: true)

Returns:

  • (String)

    Joined string of filtered and transformed elements



28
29
30
31
32
33
34
35
36
# File 'lib/everythingrb/core/enumerable.rb', line 28

def join_map(join_with = "", with_index: false, &block)
  block = ->(i) { i } if block.nil?

  if with_index
    filter_map.with_index(&block).join(join_with)
  else
    filter_map(&block).join(join_with)
  end
end