Deep set

hash = { }
def deep_set(hash, value, keys)
keys[0...-1].inject(hash) do |acc, h|
v = acc.public_send(:[], h)
v ? v : acc[h] = {}
end.public_send(:[]=, keys.last, value)
end

deep_set(hash, 42, [:a, :b, :c])
deep_set(hash, 43, [:a, :b, :d])
deep_set(hash, 44, [:a, :b, :e])
puts hash

你可能感兴趣的:(Deep set)