Class: Array
Instance Method Summary collapse
-
#can_merge?(other) ⇒ Boolean
Checks if other can be merged with this array.
-
#deep_dup ⇒ Array
Creates deep copy of array with all nested structures.
-
#deep_merge!(other, array_strategy: nil) ⇒ self
Deep merges other array into self, modifying receiver.
Methods included from IS::Deep
Instance Method Details
#can_merge?(other) ⇒ Boolean
Checks if other can be merged with this array.
165 166 167 |
# File 'lib/is-deep.rb', line 165 def can_merge? other other.is_a?(Array) || other.respond_to?(:to_ary) end |
#deep_dup ⇒ Array
Creates deep copy of array with all nested structures.
Handles circular references correctly.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/is-deep.rb', line 106 def deep_dup visited_wrap do |visited| self_id = self.object_id return visited[self_id] if visited.has_key?(self_id) result = [] visited[self_id] = result self.each do |item| id = item.object_id value = if visited.has_key?(id) visited[id] elsif item.respond_to?(:deep_dup) visited[id] = item.deep_dup elsif item.respond_to?(:dup) visited[id] = item.dup else visited[id] = item end result << value end result end end |
#deep_merge!(other, array_strategy: nil) ⇒ self
Deep merges other array into self, modifying receiver.
Uses configured or provided array_strategy to determine merge semantics. Strategy receives (base, other) and returns result array.
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/is-deep.rb', line 138 def deep_merge! other, array_strategy: nil visited_wrap do |visited| id = self.object_id return self if visited.has_key?(id) visited[id] = self source = if other.is_a?(Array) other elsif other.respond_to?(:to_ary) other.to_ary else raise ArgumentError, "Unsupported type of source: (#{other.class})", caller_locations end strategy = array_strategy || IS::Deep.array_strategy result = strategy.call(self, source) self.clear result.each { |item| self << item } self end end |