是的,這是因爲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}]