【问题标题】:Array of hashes in loop, rewriting hash values during each iteration循环中的哈希数组,在每次迭代期间重写哈希值
【发布时间】:2014-03-02 01:42:16
【问题描述】:

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

# 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

似乎数组只保存了最后一次迭代的哈希值。这方面有什么建议吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    是的,这是因为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}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-15
      • 2019-06-03
      • 2023-04-07
      • 2012-03-05
      • 2015-11-08
      • 2013-08-20
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多