ruby - create nested hash from a list -
i have got list l = [:foo, :bar, :baz]
, want assign varible hash h ={}
programmatically.
hash should like
{ foo: { bar: { baz: some_value } } }
note: keys variables!
question:
- how can this?
you use inject
on reversed list :
l = [:foo, :bar, :baz] h = l.reverse.inject(:some_value) |value, key| { key => value } end p h # {:foo=>{:bar=>{:baz=>:some_value}}}
reverse
used in order build innermost hash first, , keep building nested hash outwards.
Comments
Post a Comment