gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:37 25 4
gpt4 key购买 nike

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

# 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

似乎该数组只保存最后一次迭代的哈希值。对此有什么建议吗?

最佳答案

是的,这是因为 Hash 对象总是持有唯一的键,而键持有最新更新的值。现在在 each 方法中,您不断更新与 "Current element""Current iteration" 相同的键,用于数组的每次迭代 搜索。正如我上面所说,哈希中的键始终保存最新更新的值,因此您的哈希也保存最后一次迭代值。

现在,您将相同的 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}]

关于ruby - 循环中的哈希数组,在每次迭代期间重写哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com