Ruby循环/使用具有不同数据点的散列键将数据注入到数组中

时间:2016-03-16 01:38:29

标签: arrays ruby loops hash

将两个来源的数据注入相同的哈希

时遇到一些问题

例如:

 hash = Hash[board_members_ids.map {|x| [x, :name => nil, :title => nil]}]
 hash => {"IQ788201"=>{:name=>nil, :title=>nil},
"IQ534595"=>{:name=>nil, :title=>nil},
"IQ534605"=>{:name=>nil, :title=>nil},
"IQ10049084"=>{:name=>nil, :title=>nil},
"IQ10049098"=>{:name=>nil, :title=>nil},
"IQ24982164"=>{:name=>nil, :title=>nil},
"IQ534637"=>{:name=>nil, :title=>nil},
"IQ534648"=>{:name=>nil, :title=>nil},
"IQ24245395"=>{:name=>nil, :title=>nil},
"IQ145953536"=>{:name=>nil, :title=>nil},
"IQ268369821"=>{:name=>nil, :title=>nil}}

我现在有一个带有ID键的哈希值。现在我有另一个数组,其中包含需要为每个键的名称注入的相应顺序的数据。

示例:

board_members_names = ["blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8", "blah9", "blah10", "blah11"]

我在散列上使用.store方法很好但是:

我正在尝试遍历哈希并将每个“board_member_names”作为值插入:name值按照给定的数组的顺序排列 - 并且似乎总是在数组中插入第一个值它们

谢谢!

2 个答案:

答案 0 :(得分:0)

hash.each_with_index { |(k,v),i| hash[k][:name] = board_members_names[i] }
  # => {"IQ788201"   =>{:name=>"blah1",  :title=>nil},
  #     "IQ534595"   =>{:name=>"blah2",  :title=>nil},
  #     "IQ534605"   =>{:name=>"blah3",  :title=>nil},
  #     "IQ10049084" =>{:name=>"blah4",  :title=>nil},
  #     "IQ10049098" =>{:name=>"blah5",  :title=>nil},
  #     "IQ24982164" =>{:name=>"blah6",  :title=>nil},
  #     "IQ534637"   =>{:name=>"blah7",  :title=>nil},
  #     "IQ534648"   =>{:name=>"blah8",  :title=>nil},
  #     "IQ24245395" =>{:name=>"blah9",  :title=>nil},
  #     "IQ145953536"=>{:name=>"blah10", :title=>nil},
  #     "IQ268369821"=>{:name=>"blah11", :title=>nil}} 

答案 1 :(得分:0)

如果唯一的问题是保持秩序,这应该有用。

board_members_names = ["blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8", "blah9", "blah10", "blah11"]

hash = {"IQ788201"=>{:name=>nil, :title=>nil},
"IQ534595"=>{:name=>nil, :title=>nil},
"IQ534605"=>{:name=>nil, :title=>nil},
"IQ10049084"=>{:name=>nil, :title=>nil},
"IQ10049098"=>{:name=>nil, :title=>nil},
"IQ24982164"=>{:name=>nil, :title=>nil},
"IQ534637"=>{:name=>nil, :title=>nil},
"IQ534648"=>{:name=>nil, :title=>nil},
"IQ24245395"=>{:name=>nil, :title=>nil},
"IQ145953536"=>{:name=>nil, :title=>nil},
"IQ268369821"=>{:name=>nil, :title=>nil}}

hash.keys.each { |k| hash[k][:name] = board_members_names.shift }

puts hash.to_s

输出:

{"IQ788201"=>{:name=>"blah1", :title=>nil}, "IQ534595"=>{:name=>"blah2", :title=
>nil}, "IQ534605"=>{:name=>"blah3", :title=>nil}, "IQ10049084"=>{:name=>"blah4",
 :title=>nil}, "IQ10049098"=>{:name=>"blah5", :title=>nil}, "IQ24982164"=>{:name
=>"blah6", :title=>nil}, "IQ534637"=>{:name=>"blah7", :title=>nil}, "IQ534648"=>
{:name=>"blah8", :title=>nil}, "IQ24245395"=>{:name=>"blah9", :title=>nil}, "IQ1
45953536"=>{:name=>"blah10", :title=>nil}, "IQ268369821"=>{:name=>"blah11", :tit
le=>nil}}