예, Hash
개체는 항상 고유 키를 보유하고 키는 가장 최근의 업데이트 된 값을 보유합니다. 이제 each
메서드 내에서 search
배열을 반복 할 때마다 "Current element"
및 "Current iteration"
과 동일한 키를 계속 업데이트했습니다. 위에서 말했듯이 해시 내부의 키에는 항상 최신 업데이트 값이 저장되므로 해시에는 마지막 반복 값이 저장됩니다.
이제 배열 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}]