source: rubyforge.org/projects/facets/ version: 1.7.46 license: Ruby License NOTE: remove this method if the Facets gem is installed. BUG: weave is destructive to values in the source hash that are arrays!
(this is acceptable for RConfig's use as the basis for weave!)
Weaves the contents of two hashes producing a new hash.
# File lib/rconfig/core_ext/hash.rb, line 14 14: def weave(other_hash, clobber=false) 15: return self unless other_hash 16: unless other_hash.kind_of?(Hash) 17: raise ArgumentError, "RConfig: (Hash#weave) expected <Hash>, but was <#{other_hash.class}>" 18: end 19: 20: self_dup = self.dup # self.clone does not remove freeze! 21: 22: other_hash.each { |key, other_node| 23: 24: self_dup[key] = 25: 26: if self_node = self_dup[key] 27: 28: case self_node 29: when Hash 30: 31: # hash1, hash2 => hash3 (recursive +) 32: if other_node.is_a?(Hash) 33: 34: self_node.weave(other_node, clobber) 35: 36: # hash, array => error (Can't weave'em, must clobber.) 37: elsif other_node.is_a?(Array) && !clobber 38: 39: raise(ArgumentError, "RConfig: (Hash#weave) Can't weave Hash and Array") 40: 41: # hash, array => hash[key] = array 42: # hash, value => hash[key] = value 43: else 44: other_node 45: end 46: 47: when Array 48: 49: # array, hash => array << hash 50: # array1, array2 => array1 + array2 51: # array, value => array << value 52: unless clobber 53: case other_node 54: when Hash 55: self_node << other_node 56: when Array 57: self_node + other_node 58: else 59: self_node << other_node 60: end 61: 62: # array, hash => hash 63: # array1, array2 => array2 64: # array, value => value 65: else 66: other_node 67: end 68: 69: else 70: 71: # value, array => array.unshift(value) 72: if other_node.is_a?(Array) && !clobber 73: other_node.unshift(self_node) 74: 75: # value1, value2 => value2 76: else 77: other_node 78: end 79: 80: end # case self_node 81: 82: # Target hash didn't have a node matching the key, 83: # so just add it from the source hash. 84: # !self_dup.has_key?(key) => self_dup.add(key, other_node) 85: else 86: other_node 87: end 88: 89: } # other_hash.each 90: 91: self_dup # return new weaved hash 92: end
Same as self.weave(other_hash, dont_clobber) except that it weaves other hash to itself, rather than create a new hash.
# File lib/rconfig/core_ext/hash.rb, line 97 97: def weave!(other_hash, clobber=false) 98: weaved_hash = self.weave(other_hash, clobber) 99: self.merge!(weaved_hash) 100: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.