gpt4 book ai didi

具有重复值的数组的 ruby​​ 数组到散列的散列

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:51 26 4
gpt4 key购买 nike

我是 ruby​​ 的新手,我很难弄清楚如何将数组的数组转换为数组哈希的哈希。

例如,假设我有:

[ [38, "s", "hum"], 
[38, "t", "foo"],
[38, "t", "bar"],
[45, "s", "hum"],
[45, "t", "ram"],
[52, "s", "hum"],
[52, "t", "cat"],
[52, "t", "dog"]
]

我最终想要的是:

{38 => {"s" => ["hum"],
"t" => ["foo", "bar"]
},
45 => {"s" => ["hum"],
"t" => ["ram"]
},
52 => {"s" => ["hum"],
"t" => ["cat", "dog"]
}
}

我已经尝试过 group_by 和 Hash,但它们都无法提供我想要的东西。

最佳答案

也许有更简洁的方法,但我决定直接走:

input = [ [38, "s", "hum"],
[38, "t", "foo"],
[38, "t", "bar"],
[45, "s", "hum"],
[45, "t", "ram"],
[52, "s", "hum"],
[52, "t", "cat"],
[52, "t", "dog"]
]

output = {}

# I'll talk through the first iteration in the comments.

input.each do |outer_key, inner_key, value|
# Set output[38] to a new hash, since output[38] isn't set yet.
# If it were already set, this line would do nothing, so
# output[38] would keep its previous data.
output[outer_key] ||= {}

# Set output[38]["s"] to a new array, since output[38]["s"] isn't set yet.
# If it were already set, this line would do nothing, so
# output[38]["s"] would keep its previous data.
output[outer_key][inner_key] ||= []

# Add "hum" to the array at output[38]["s"].
output[outer_key][inner_key] << value
end

所以,你实际使用的部分,全部整理好:

output = {}

input.each do |outer_key, inner_key, value|
output[outer_key] ||= {}
output[outer_key][inner_key] ||= []
output[outer_key][inner_key] << value
end

关于具有重复值的数组的 ruby​​ 数组到散列的散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454075/

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