OLW: #Array to #Hash Chain

This is a #ruby #one-liner that lets you convert an array into a chain of hashes. For example, a set of progressively more specific terms like [“Author”,”Book”,”Chapter”,”Paragraph”,”Sentence”,”Word”] will convert to a representative hash {“Author”=>{“Book”=>{“Chapter”=>{“Paragraph”=>{“Sentence”=>”Word”}}}}}. This is useful if you want to store nested data as a flat array or array string but then later parse it out as a nested hash to more easily work with.

The code is quite simple to apply to array arr:

arr.reverse.inject{|y,x|{x=>y}}

“Sooner or later, I’ll be punctual.” – Ashleigh Brilliant

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s