Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/array_utils.rb
Instance Method Summary collapse
- #[]=(index_or_range, length = nil, value) ⇒ Object
-
#densify ⇒ Array
Returns a new array where all
nilvalues are removed. -
#densify! ⇒ self
Modifies the array in place by removing all
nilvalues. - #original_set ⇒ Object
-
#sparse?(threshold = 0.5) ⇒ Boolean
Determines whether an array is “sparse,” meaning it contains a significant proportion of
nilvalues compared to its size. -
#split_by_parity ⇒ Array
Partitions an array of integers based on parity (odd or even property).
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 |
#densify ⇒ Array
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.
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.
83 84 85 |
# File 'lib/array_utils.rb', line 83 def densify! replace(densify) end |
#original_set ⇒ Object
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.
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_parity ⇒ Array
Partitions an array of integers based on parity (odd or even property)
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 |