Skip to content

Instantly share code, notes, and snippets.

@timakin
Created July 30, 2016 14:44
Show Gist options
  • Save timakin/629643578ca8b3de3ac0ead91061e1c7 to your computer and use it in GitHub Desktop.
Save timakin/629643578ca8b3de3ac0ead91061e1c7 to your computer and use it in GitHub Desktop.
deep_insert
hash = {"some_key" => "value",
"nested" => {"key1" => "val1",
"key2" => "val2",
"key3" => {
"nenene" => "aa"
}}}
class Hash
def insert_before(key, kvpair)
arr = to_a
pos = arr.index(arr.assoc(key))
if pos
arr.insert(pos, kvpair)
else
arr << kvpair
end
replace Hash[arr]
end
def deep_insert(*keys, key, val)
keys.inject(self) {|h, k|
h[k]
}[key] = val
end
end
keys = "nested.key3"
splitted = keys.split(".")
p splitted
p *splitted
p hash.deep_insert(*splitted, "nene", "oh")
#hash[*splitted].insert_before('key2', ['new_key', { "keke" => 'new_value' }])
p hash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment