×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Ruby
Posted by: Yaroslav Sidlovsky
Added: Oct 19, 2017 3:13 PM
Modified: Oct 19, 2017 3:14 PM
Views: 16
Tags: hash ruby
  1. class Hash
  2.   def dot_path_set(key_path, value)
  3.     key, sub_key = key_path.split('.', 2)
  4.  
  5.     if sub_key.nil?
  6.       self[key] = value
  7.     else
  8.       if self[key].nil?
  9.         self[key] = {}
  10.       end
  11.       self[key].dot_path_set(sub_key, value)
  12.     end
  13.   end
  14.  
  15.   def dot_path_get(key)
  16.     parts = key.split('.', 2)
  17.     match = self[parts[0]]
  18.     if !parts[1] or match.nil?
  19.       match
  20.     else
  21.       match.dot_path_get(parts[1])
  22.     end
  23.   end
  24. end
  25.  
  26. # Usage:
  27.  
  28. h = {}
  29. # => {}
  30.  
  31. h.dot_path_set('a.b.c.d.e', 1)
  32. # => 1
  33.  
  34. h
  35. # => {"a"=>{"b"=>{"c"=>{"d"=>{"e"=>1}}}}}
  36.  
  37. h.dot_path_get('a.b.c.d.e')
  38. # => 1