class Hash

this is borrowed from rails

this is borrowed from rails

Public Instance Methods

deep_dup() click to toggle source

Returns a deep copy of hash.

hash = { :a => { :b => 'b' } }
dup  = hash.deep_dup
dup[:a][:c] = 'c'

hash[:a][:c] #=> nil
dup[:a][:c]  #=> "c"
# File lib/helper/deep_dup.rb, line 12
def deep_dup
  duplicate = self.dup
  duplicate.each_pair do |k,v|
    tv = duplicate[k]
    duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
  end
  duplicate
end
deep_merge(other_hash) click to toggle source

Returns a new hash with self and other_hash merged recursively.

h1 = {:x => {:y => [4,5,6]}, :z => [7,8,9]}
h2 = {:x => {:y => [7,8,9]}, :z => "xyz"}

h1.deep_merge(h2) #=> { :x => {:y => [7, 8, 9]}, :z => "xyz" }
h2.deep_merge(h1) #=> { :x => {:y => [4, 5, 6]}, :z => [7, 8, 9] }
# File lib/helper/deep_merge.rb, line 11
def deep_merge(other_hash)
  dup.deep_merge!(other_hash)
end
deep_merge!(other_hash) click to toggle source

Same as deep_merge, but modifies self.

# File lib/helper/deep_merge.rb, line 16
def deep_merge!(other_hash)
  other_hash.each_pair do |k,v|
    tv = self[k]
    self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
  end
  self
end
path(hashPath) click to toggle source

Returns the element at the end of the defined path

the path should be in format of "a/:b/c", symbols treated as symbols
then a string interpreation expression is build like
"self['a'][:b][c]"

known issue: path segments with slashes are not supported
# File lib/helper/hash_path_eval.rb, line 9
def path(hashPath)
  return self if hashPath.nil? or hashPath.empty?

  hashPath = hashPath.split('/').map{ |v| v.start_with?(":") ? "[#{v}]" : "['#{v}']" }.join
  hashPath = "self#{hashPath}"
  
  eval hashPath
rescue
  nil
end