Guest User

Untitled

a guest
Jul 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. t('one.two.three.four')
  2.  
  3. path.split(".").inject(hash) { |hash, key| hash[key] }
  4.  
  5. def convert_hash(hash, path = "")
  6. hash.each_with_object({}) do |(k, v), ret|
  7. key = path + k
  8.  
  9. if v.is_a? Hash
  10. ret.merge! convert_hash(v, key + ".")
  11. else
  12. ret[key] = v
  13. end
  14. end
  15. end
  16.  
  17. class Hash
  18. def dig(dotted_path)
  19. parts = dotted_path.split '.', 2
  20. match = self[parts[0]]
  21. if !parts[1] or match.nil?
  22. return match
  23. else
  24. return match.dig(parts[1])
  25. end
  26. end
  27. end
  28.  
  29. my_hash = {'a' => {'b' => 'a-b', 'c' => 'a-c', 'd' => {'e' => 'a-d-e'}}, 'f' => 'f'}
  30. my_hash.dig('a.d.e') # outputs 'a-d-e' (by calling my_hash['a']['d']['e'])
Add Comment
Please, Sign In to add comment