我有散列的散列(@post),我想在其中保持散列键在数组(@post_csv_order)中的顺序,还想保持关系键=>数组中的值。
我不知道数组中 @post 哈希和 key => value 元素的最终数量。
我不知道如何在循环中为数组中的所有元素分配散列。一个接一个 @post_csv_order[0][0] => @post_csv_order[0][1]
效果很好。
# 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
期望的哈希分配应该是这样的
{123=>{"帖子标题"=>"测试帖", "ForumID"=>123}}
最佳答案
最好的方法是使用to_h
:
[ [:foo,1],[:bar,2],[:baz,3] ].to_h #=> {:foo => 1, :bar => 2, :baz => 3}
注意:这是在 Ruby 2.1.0 中引入的。对于较旧的 Ruby,您可以使用我的 backports
gem 和 require 'backports/2.1.0/array/to_h'
, 或者使用 Hash[]
:
array = [[:foo,1],[:bar,2],[:baz,3]]
# then
Hash[ array ] #= > {:foo => 1, :bar => 2, :baz => 3}
这在 Ruby 1.8.7 及更高版本中可用。如果您仍在使用 Ruby 1.8.6,您可以 require "backports/1.8.7/hash/constructor"
,但您也可以使用 to_h
向后移植。
关于ruby - 当 (key => value) 存储在数组中时的哈希赋值? ( ruby ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2126673/