module HashExtensions::InstanceMethods
InstanceMethods
module
Public Instance Methods
all_keys_with_path(parent = nil)
click to toggle source
get all keys with path, { 'a' => 'v1', 'b' => { 'c' => 'v2'}}.all_keys_with_path => ['a','b.c']
# File lib/eventhub/hash_extensions.rb, line 30 def all_keys_with_path(parent = nil) a = [] each do |k, v| a << if v.is_a?(Hash) v.all_keys_with_path([parent, k].compact.join(".")) else [parent, k].compact.join(".").to_s end end a.flatten end
get(arg)
click to toggle source
get value from provided key path e.g. hash.get(%w(event_hub plate.queue1 retry_s)) “a” => { “b” => { “c” => { “value”}}}
# File lib/eventhub/hash_extensions.rb, line 12 def get(arg) path = arg.is_a?(String) ? arg.split(".") : arg path.inject(self, :[]) end
set(arg, value, overwrite = true)
click to toggle source
set value from provided key path, e.h. hash.set('a.b.c','new value') if overwrite is false, value will be set if it was nil previously
# File lib/eventhub/hash_extensions.rb, line 19 def set(arg, value, overwrite = true) *key_path, last = arg.is_a?(String) ? arg.split(".") : arg if overwrite key_path.inject(self) { |h, key| h.key?(key) ? h[key] : h[key] = {} } [last] = value else key_path.inject(self) { |h, key| h.key?(key) ? h[key] : h[key] = {} } [last] ||= value end end