ruby inject recursion?

Posted by Matt Humphrey on Stack Overflow See other posts from Stack Overflow or by Matt Humphrey
Published on 2011-02-15T07:22:20Z Indexed on 2011/02/15 7:25 UTC
Read the original article Hit count: 201

Filed under:
|
|
|

the goal is to start with ['a','b','c'] and end up with {'a'=>{'b'=>{'c'=>{}}}}

so, getting my bearings, i did this:

ruby-1.8.7-p174 > ['a','b','c'].inject({}){|h,v| h.update(v => {})} => {"a"=>{}, "b"=>{}, "c"=>{}}

and then figured, if i actually pass on the result hash, it will recurse and nest, but:

ruby-1.8.7-p174 > ['a','b','c'].inject({}){|h,v| h.update(v => {}); h[v]} => {}

why is this? any idea how to achieve the desired result in an elegant one-liner?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about hash