2014-03-02 61 views
1

我正在使用循環在每次迭代期間更改散列值。然後,我嘗試在每次迭代結束時將新的哈希值推送(添加)到數組中。循環中的散列數組,每次迭代期間重寫散列值

# Array and hash to hold response 
response = [] 
test_data = Hash.new  

# Array of search elements for loop 
search = ["testOne", "testTwo", "testThree"]  

current_iteration = 0 

# Loop through search words and get data for each 
search.each do |element| 

    test_data["Current element"] = element 
    test_data["Current iteration"] = current_iteration 

    response.push(test_data) 
    current_iteration += 1 
end 

看來,該數組只是持有最終迭代的哈希值。有關於此的任何提示?

回答

2

是的,這是因爲Hash對象始終保存唯一鍵,並且鍵保留最新的更新值。現在在each方法中,對於通過數組search的每次迭代,您一直在更新與"Current element""Current iteration"相同的密鑰。正如我上面所說的,散列中的鍵總是保存最新的更新值,所以你的散列也保存最後一次迭代值。

現在,您正在將相同的hash對象推向數組,因此最終在陣列response內部獲得了相同的3個哈希值。你想達到什麼,以滿足你需要使用Object#dup

更正代碼:

response = [] 
test_data = hash.new  

# array of search elements for loop 
search = ["testone", "testtwo", "testthree"]  

current_iteration = 0 

# loop through search words and get data for each 
search.each do |element| 

    test_data["current element"] = element 
    test_data["current iteration"] = current_iteration 

    response.push(test_data.dup) 
    current_iteration += 1 
end 

response 
# => [{"current element"=>"testone", "current iteration"=>0}, 
#  {"current element"=>"testtwo", "current iteration"=>1}, 
#  {"current element"=>"testthree", "current iteration"=>2}] 

優雅的方式來做到這一點:

search = ["testone", "testtwo", "testthree"]  

response = search.map.with_index do |element,index| 
    {"current element" => element, "current iteration" => index} 
end 

response 
# => [{"current element"=>"testone", "current iteration"=>0}, 
#  {"current element"=>"testtwo", "current iteration"=>1}, 
#  {"current element"=>"testthree", "current iteration"=>2}]