循环中的哈希数组,在每次迭代期间重写哈希值

时间:2014-03-02 01:42:17

标签: ruby

我正在使用一个循环,在每次迭代期间更改哈希值。然后我尝试在每次迭代结束时将新的哈希值推送(添加)到数组中。

# 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

似乎数组只保存最后一次迭代的哈希值。关于这个的任何提示?

1 个答案:

答案 0 :(得分:3)

是的,这是因为Hash对象始终包含唯一键,并且键包含最新的更新值。现在,在each方法中,对于通过数组"Current element"的每次迭代,您都会继续更新与"Current iteration"search相同的键。如上所述,哈希中的键始终保存最新的更新值,因此您的哈希值也保留最后一个迭代值。

现在,您正在数组hash内推送相同的response对象,因此最终您在数组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}]