Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/array_utils.rb

Instance Method Summary collapse

Instance Method Details

#[]=(index_or_range, length = nil, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/array_utils.rb', line 6

def []=(index_or_range, length = nil, value)
  if length.nil?
    if index_or_range.is_a?(Integer) && index_or_range >= size
      push(value)
    elsif index_or_range.is_a?(Range)
      original_set(index_or_range, value) # Handle range assignment
    else
      original_set(index_or_range, value)
    end
  else
    original_set(index_or_range, length, value) # Handle slice assignment
  end
end

#densifyArray

Returns a new array where all nil values are removed.

If an element is an array, it is compacted (removing nil values) before being added. This makes it more effective than the default #compact method which only works with 1D arrays.

Returns:

  • A new array with nil values removed.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/array_utils.rb', line 58

def densify
  densified_array = []

  each do |elem|
    next unless elem

    if elem.is_a? Array
      nested = elem.densify
      # skip empty arrays after removing nil values
      densified_array << nested unless nested.empty?
    else
      densified_array << elem
    end
  end

  densified_array
end

#densify!self

Modifies the array in place by removing all nil values.

If an element is an array, it is compacted (removing nil values) before being added. This makes it more effective than the default #compact method which only works with 1D arrays.

Returns:

  • The modified array.



83
84
85
# File 'lib/array_utils.rb', line 83

def densify!
  replace(densify)
end

#original_setObject



4
# File 'lib/array_utils.rb', line 4

alias_method :original_set, :[]=

#sparse?(threshold = 0.5) ⇒ Boolean

Determines whether an array is “sparse,” meaning it contains a significant proportion of nil values compared to its size.

Examples:

Basic usage:

[1, nil, nil, 4, nil].sparse? # => true (more than 50% nil values)

Custom threshold:

[1, nil, nil, 4, 5].sparse?(0.8) # => false (less than 80% nil values)

Non-sparse array:

[1, 2, 3, 4, 5].sparse? # => false (no nil values)

Parameters:

  • (defaults to: 0.5)

    The threshold ratio (default: 0.5). If the proportion of nil values to the array’s size exceeds this threshold, the array is considered sparse.

Returns:

  • true if the array is sparse, false otherwise.



47
48
49
# File 'lib/array_utils.rb', line 47

def sparse?(threshold = 0.5)
  flatten.count(nil).to_f / flatten.size > threshold
end

#split_by_parityArray

Partitions an array of integers based on parity (odd or even property)

Returns:

  • An nested array of odd and even numbers.

Raises:



23
24
25
26
27
# File 'lib/array_utils.rb', line 23

def split_by_parity
  raise TypeError, "Expected only numbers" unless all?(Numeric)

  partition(&:odd?)
end