-1

我有一个哈希值,所有值都是空白的。

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

get_row_datas 正在获取作为数组的数据。

[[约翰1,约翰2,0123],[约翰3,约翰4,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:无法在迭代期间将新键添加到哈希中

4

1 回答 1

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}]

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

原因如下:

地图{ |项目| 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}]
于 2013-06-23T06:46:59.770 回答