Skip to content

Instantly share code, notes, and snippets.

@westonganger
Last active October 25, 2021 20:16
Show Gist options
  • Select an option

  • Save westonganger/53b098b5de488d3f57c38d85dc4fc10b to your computer and use it in GitHub Desktop.

Select an option

Save westonganger/53b098b5de488d3f57c38d85dc4fc10b to your computer and use it in GitHub Desktop.
Ruby Hash deep_set
Hash.class_eval do
def deep_set(keys_array, val)
keys_array[0...-1].inject(self){|result, key|
if !result[key].is_a?(Hash)
result[key] = {}
end
result[key]
}.send(:[]=, keys_array.last, val)
return self
end
end
h = {}
h.deep_set([:foo, :bar, :asd], "foobar")
h # => { foo: { bar: { asd: "foobar" } } }
class Helper
def self.deep_set(hash, keys_array, val)
if !hash.is_a?(::Hash)
raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash")
end
keys_array[0...-1].inject(hash){|result, key|
if !result[key].is_a?(Hash)
result[key] = {}
end
result[key]
}.send(:[]=, keys_array.last, val)
return hash
end
end
h = {}
Helper.hash_deep_set(h, [:foo, :bar, :asd], "foobar")
h # => { foo: { bar: { asd: "foobar" } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment