在 ruby 中迭代哈希列表的最佳方法

Best way to iterate a list of hash in ruby

我有类似 List< HashMap< String, List>> 的数据结构:

records = [{"1"=>[{"account_id"=>"1", "v"=>"1"}, {"account_id"=>"1", "v"=>"2"}, {"account_id"=>"1", "v"=>"3"}, {"account_id"=>"1", "v"=>"4"]}, {"2"=>[{"account_id"=>"2", "v"=>"4"}, {"account_id"=>"2", "v"=>"4"}, {"account_id"=>"2", "v"=>"4"}]}]

我不关心 hashmap 中的键(在本例中为“1”和“2”),而是想按组迭代 map 的值:

records.each do |account_map| 
    account_record = account_map.values[0] # This line
        for i in (0 ... account_record.size - 1)
            #do something and update account_record[i]
        end
    end
end

如何将 account_record = account_map.values[0] 合并到 each 循环中或使其看起来更好。谢谢

你的例子很混乱,但是迭代散列的常规方法如下

hash.each do |key, value|
end

因此在您的示例中,您应该这样做

records.each do |account_map| 
    account_map.each do |index, array|
        array.each do |hash|
            hash['account_id'] # This is how you access your data
            hash['v']          # This is how you access your data
        end
    end
end

当然你应该使用比索引、数组和散列更好的变量名。