Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created July 31, 2018 09:43
Show Gist options
  • Save wojtha/975e0599ac3c19df1b9eb9295cc99ed3 to your computer and use it in GitHub Desktop.
Save wojtha/975e0599ac3c19df1b9eb9295cc99ed3 to your computer and use it in GitHub Desktop.
Hash deep set in ruby
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