Created
July 31, 2018 09:43
-
-
Save wojtha/975e0599ac3c19df1b9eb9295cc99ed3 to your computer and use it in GitHub Desktop.
Hash deep set in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Query | |
attr_reader :query | |
def initialize | |
@query = { b: 2 } | |
end | |
def deep_set(*keys, val) | |
key = keys.pop | |
keys.inject(query) { |hsh, k| hsh.key?(k) ? hsh[k] : hsh[k] = {}; hsh[k] }[key] = val | |
end | |
end | |
q = Query.new | |
keys = [:a, :b] | |
q.deep_set(*keys, 1) | |
p q.query.inspect # => "{:b=>2, :a=>{:b=>1}}" | |
p keys # => [:a, :b] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment