gpt4 book ai didi

ruby - 通过另一个哈希过滤 Ruby 哈希数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:46 27 4
gpt4 key购买 nike

也许我遗漏了一些明显的东西。用另一个散列或多个键/值对过滤一个散列似乎很棘手。

fruit = [
{ name: "apple", color: "red", pieable: true },
{ name: "orange", color: "orange", pieable: false },
{ name: "grape", color: "purple", pieable: false },
{ name: "cherry", color: "red", pieable: true },
{ name: "banana", color: "yellow", pieable: true },
{ name: "tomato", color: "red", pieable: false }
]
filter = { color: "red", pieable: true }

# some awesome one-liner? would return
[
{ name: "apple", color: "red", pieable: true },
{ name: "cherry", color: "red", pieable: true }
]

我认为哈希数组不是问题所在。我什至不知道如何通过另一个任意哈希来测试哈希。我正在使用 Rails,所以 active_support 等之外的任何东西都可以。

最佳答案

可以做成一个衬垫。但是多行更简洁。

fruit.select do |hash| # or use select!
filter.all? do |key, value|
value == hash[key]
end
end

关于ruby - 通过另一个哈希过滤 Ruby 哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628686/

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