2014-03-02 1 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"과 동일한 키를 계속 업데이트했습니다. 위에서 말했듯이 해시 내부의 키에는 항상 최신 업데이트 값이 저장되므로 해시에는 마지막 반복 값이 저장됩니다.

이제 배열 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}]