Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/everythingrb/core/array.rb

Instance Method Summary collapse

Instance Method Details

#deep_freezeself

Recursively freezes self and all of its contents

Examples:

Freeze an array with nested structures

["hello", { name: "Alice" }, [1, 2, 3]].deep_freeze
# => All elements and nested structures are now frozen

Returns:

  • (self)

    Returns the frozen array



80
81
82
83
# File 'lib/everythingrb/core/array.rb', line 80

def deep_freeze
  each { |v| v.respond_to?(:deep_freeze) ? v.deep_freeze : v.freeze }
  freeze
end

#dig_map(*keys) ⇒ Array

Maps over hash keys to extract nested values using dig

Examples:

[
  {user: {profile: {name: 'Alice'}}},
  {user: {profile: {name: 'Bob'}}}
].dig_map(:user, :profile, :name)
# => ['Alice', 'Bob']

Parameters:

  • keys (Array<Symbol, String>)

    The keys to dig through

Returns:

  • (Array)

    Array of nested values



67
68
69
# File 'lib/everythingrb/core/array.rb', line 67

def dig_map(*keys)
  map { |v| v.dig(*keys) }
end

#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/array.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

#key_map(key) ⇒ Array

Maps over hash keys to extract values for a specific key

Examples:

[{name: 'Alice', age: 30}, {name: 'Bob', age: 25}].key_map(:name)
# => ['Alice', 'Bob']

Parameters:

  • key (Symbol, String)

    The key to extract

Returns:

  • (Array)

    Array of values



49
50
51
# File 'lib/everythingrb/core/array.rb', line 49

def key_map(key)
  map { |v| v[key] }
end