30

I have the following:

value = 42  
array = ["this","is","a","test"]

how can I convert that to get this

{ "this" => { "is" => { "a" => { "test" => 42 } } } }

the array is always flat.

Thank you!

3
  • 1
    Now that's an insane data structure... would it happen to have any justification? Commented Feb 23, 2011 at 18:15
  • 2
    @delnan "hi.i.am.some.kind.of.path=value" to be merged in an existing yaml hash dump. Commented Feb 23, 2011 at 18:24
  • 1
    @delnan Another example would be to eager load a bunch of chained tables specified by an "array" like join1:join2:join3:column1. So I would need to eager_load(join1: {join2: :join3}) Commented May 18, 2018 at 20:43

1 Answer 1

110

Try this:

array.reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
#=> {"this"=>{"is"=>{"a"=>{"test"=>42}}}}
Sign up to request clarification or add additional context in comments.

4 Comments

The most difficult part of this was figuring out how to phrase my question on SO. "Nested" was the turning point ;)
You have achieved what I have been trying to achieve in about 50 lines less than my best attempt LOL.
Somebody needs to explain how this magic works. Been trying to do this unsuccessfully for 60 minutes.
Okay, I'll explain for myself and others. Firstly, this is clever in its simplicity. Using reverse and inject it first creates a Hash with the last key ("test") and the final value (42). It then takes that Hash and assigns it to the second last key ("a") and keeps going until it reaches the first key in the original Array. The result is a perfectly nested Hash. Nice one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.