Module: Enumerable

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

Overview

Extensions to Ruby’s core Enumerable module

These additions make working with any enumerable collection more expressive by combining common operations into convenient methods.

Examples:

Using join_map with a Range

(1..5).join_map(" | ") { |n| "item-#{n}" if n.even? }
# => "item-2 | item-4"

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"

Using with other enumerables

(1..10).join_map(" | ") { |n| "num#{n}" if n.even? }
# => "num2 | num4 | num6 | num8 | num10"

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 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



38
39
40
41
42
43
44
45
46
# File 'lib/everythingrb/core/enumerable.rb', line 38

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