Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/hash_tools.rb
Instance Method Summary collapse
- #create_empty_node(path) ⇒ Object
- #create_path_if_not_exist(path) ⇒ Object
-
#find_by_path(path) ⇒ Object
Finds value in hash by path example: hash = { a => ‘foo’, b => { ba => { bac => ‘bar’ } } } >>>.
- #next_path(path) ⇒ Object
- #nodes_array(path = []) ⇒ Object
- #paths ⇒ Object
- #previous_path(path) ⇒ Object
- #update_by_path(path, string) ⇒ Object
- #update_by_path_wo_parents(path, string) ⇒ Object
Instance Method Details
#create_empty_node(path) ⇒ Object
57 58 59 60 |
# File 'lib/hash_tools.rb', line 57 def create_empty_node(path) return false if not find_by_path(path).nil? update_by_path_wo_parents(path, {}) end |
#create_path_if_not_exist(path) ⇒ Object
62 63 64 65 66 67 68 69 |
# File 'lib/hash_tools.rb', line 62 def create_path_if_not_exist(path) aa = path_to_a(path) new_aa = [] aa.each do |a| new_aa << a create_empty_node(a_to_path(new_aa)) end end |
#find_by_path(path) ⇒ Object
Finds value in hash by path example: hash = {
a => 'foo',
b => {
ba => {
bac => 'bar'
}
}
}
14 15 16 17 18 19 20 21 22 |
# File 'lib/hash_tools.rb', line 14 def find_by_path(path) e ="self" path_to_a(path).each{|i| e = e+"['#{i}']" } begin eval(e) rescue NoMethodError return nil end end |
#next_path(path) ⇒ Object
87 88 89 90 |
# File 'lib/hash_tools.rb', line 87 def next_path(path) paths = self.paths paths[paths.index(path) + 1] end |
#nodes_array(path = []) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/hash_tools.rb', line 71 def nodes_array(path = []) ret = [] self.each do |key,value| if value.class == Hash ret = ret + value.nodes_array(path + [key]) else ret << path + [key] end end ret end |
#paths ⇒ Object
83 84 85 |
# File 'lib/hash_tools.rb', line 83 def paths self.nodes_array.map{|i| i.join(".")} end |
#previous_path(path) ⇒ Object
92 93 94 95 |
# File 'lib/hash_tools.rb', line 92 def previous_path(path) paths = self.paths paths[paths.index(path) - 1] end |
#update_by_path(path, string) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/hash_tools.rb', line 25 def update_by_path(path, string) return false if find_by_path(path).class == "Hash" create_path_if_not_exist(path) e ="self" path_a = path_to_a(path) path_a.each{|i| e = e+"['#{i}']" } string = string.gsub(/^[ \t]+/,"") e = e+"='#{string}'" begin eval(e) return true rescue => e return [false, e] end end |
#update_by_path_wo_parents(path, string) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/hash_tools.rb', line 42 def update_by_path_wo_parents(path, string) return false if find_by_path(path).class.to_s == "Hash" && find_by_path(path).length > 0 e ="self" path_a = path_to_a(path) path_a.each{|i| e = e+"['#{i}']" } #string = string.gsub(/^[ \t]+/,"") e = e+"=string" begin eval(e) return true rescue return false end end |