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}}
In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.
Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.
The best way is to use to_h
:
[ [:foo,1],[:bar,2],[:baz,3] ].to_h #=> {:foo => 1, :bar => 2, :baz => 3}
Note: This was introduced in Ruby 2.1.0. For older Ruby, you can use my backports
gem and require 'backports/2.1.0/array/to_h'
, or else use Hash[]
:
array = [[:foo,1],[:bar,2],[:baz,3]]
# then
Hash[ array ] #= > {:foo => 1, :bar => 2, :baz => 3}
This is available in Ruby 1.8.7 and later. If you are still using Ruby 1.8.6 you could require "backports/1.8.7/hash/constructor"
, but you might as well use the to_h
backport.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With