I have hash (@post) of hashes where I want to keep the order of the hash's keys in the array (@post_csv_order) and also want to keep the relationship key => value in the array.
I don't know the final number of both @post hashes and key => value elements in the array.
I don't know how to assign the hash in a loop for all elements in the array. One by one @post_csv_order[0][0] => @post_csv_order[0][1]
works nicely.
# require 'rubygems'
require 'pp'
@post = {}
forum_id = 123 #only sample values.... to make this sample script work
post_title = "Test post"
@post_csv_order = [
["ForumID" , forum_id],
["Post title", post_title]
]
if @post[forum_id] == nil
@post[forum_id] = {
@post_csv_order[0][0] => @post_csv_order[0][1],
@post_csv_order[1][0] => @post_csv_order[1][1]
#@post_csv_order.map {|element| element[0] => element[1]}
#@post_csv_order.each_index {|index| @post_csv_order[index][0] => @post_csv_order[index][1] }
}
end
pp @post
desired hash assignment should be like that
{123=>{"Post title"=>"Test post", "ForumID"=>123}}
Answers summary
working code #1
@post[forum_id] = @post_csv_order.inject({}) {|h,e| h[e[0]] = e[1]; h}
working code #2
@post[forum_id] = Hash[*@post_csv_order.flatten]
working code #3
@post[forum_id] ||= Hash[ @post_csv_order ] #requires 'require "backports"'