2013-06-23 147 views
-1

我有一個散列,所有的值都是空白的。通過迭代分配哈希值ruby

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

get_row_datas正在獲取作爲數組的數據。

[[john1, john2, 0123], [john3, john4, 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:在迭代

+0

你的問題是什麼? – oldergod

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

but I did that with map! but not map, do you know what cause that?

原因如下:

map { |item| block } → new_ary: Creates a new array containing the values returned by the block.

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

map! {|item| block } → ary: Invokes the given block once for each element of self, replacing the element with the value returned by the block

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

嗨,謝謝!但我用地圖做了這個!但不是地圖,你知道是什麼原因嗎? – Nich

+0

@Nich看到我的貼子我回答了你的問題..;) –

+1

很酷,那是個詳細答案:) – Nich