是的,这是因为Hash 对象始终持有唯一的键,并且键与它一起保存最新更新的值。现在,在each 方法中,您将不断更新与"Current element" 和"Current iteration" 相同的键,以用于遍历数组search 的每次迭代。正如我上面所说,哈希中的键始终保存最新更新的值,因此您的哈希也保存最后一次迭代值。
现在,您在数组response 中推送相同的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}]