通过迭代ruby分配哈希值

时间:2013-06-23 06:37:36

标签: ruby hash iteration

我的哈希值都是空白的。

  

hash_obj = {:username => '',:name => '',:phone => ''}

get_row_datas正在获取数据,这是一个数组。

  

[[john1,john2,0123],[john3,j​​ohn4,345]]

我试图将这些值分配到hash_obj中,以便它变为

  

hash_array = {:username => ' john1',:name => ' john2',:phone =>   ' 0123'},{:username => ' john3',:name => ' john4',:phone => ' 345'}

def get_hash_array
  first_row_data = get_first_row
  hash_obj = Hash.new
  first_row_data.each do |column|
    hash_obj[column.to_sym] = ''
  end

  hash_array = Hash.new

  row_datas = get_row_datas
  row_datas.each_with_index do |row, row_count|
    puts "Rows datas #{row} and row count is #{row_count}"
    hash_obj.each_with_index do |attribute, attribute_count|
      hash_obj[attribute] = row[attribute_count] //problem occurs
      puts "This is attribute #{attribute} and count #{attribute_count}"
      puts "#{row[attribute_count]}"
    end
  end

  hash_obj
end

我想问一下如何赋值,因为你可以看到我的代码,会出现错误。 RuntimeError:在迭代期间无法将新密钥添加到哈希

1 个答案:

答案 0 :(得分:2)

您也可以尝试以下技术:

hash_obj = {:username => '', :name => '', :phone => ''}
val = [[:john1, :john2, 0123], [:john3,:john4, 345]]

val.map{|i| Hash[hash_obj.keys.zip(i)]}
# => [{:username=>:john1, :name=>:john2, :phone=>83},
#     {:username=>:john3, :name=>:john4, :phone=>345}]
  

但我用地图做到了!但不是地图,你知道是什么原因吗?

原因如下:

  

map {| item | block}→new_ary 创建一个包含块返回值的新数组。

hash_obj = {:username => '', :name => '', :phone => ''}
val = [[:john1, :john2, 0123], [:john3,:john4, 345]]
new_hash = val.map{|i| Hash[hash_obj.keys.zip(i)]}
val
# => [[:john1, :john2, 83], [:john3, :john4, 345]]
  

<强>图! {|项目| block}→ary :为self的每个元素调用给定的块一次,用块返回的值替换元素

hash_obj = {:username => '', :name => '', :phone => ''}
val = [[:john1, :john2, 0123], [:john3,:john4, 345]]
new_hash = val.map!{|i| Hash[hash_obj.keys.zip(i)]}
val
# => [{:username=>:john1, :name=>:john2, :phone=>83},
#     {:username=>:john3, :name=>:john4, :phone=>345}]