2, :name-6ren">
gpt4 book ai didi

ruby - 比较两个哈希数组并返回新对象

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

我有两个哈希数组。

burgers = [
{:id => 1, :name => "cheese burger"},
{:id => 2, :name => "royale"},
{:id => 3, :name => "big mac"},
{:id => 4, :name => "angus beef"}
]

eaten = [
{:burger_id => 1},
{:burger_id => 2}
]

我想返回一个数组或未吃的汉堡,其中 burgers[:id] 不等于 eaten[:burger_id]。在 burgers_not_eaten_method 中,我得到了预期的返回值。

def burgers_not_eaten
#Not sure how to compare burger[:id] with eaten[:burger_id]
burgers.reject { |burger| burger[:id] == #eaten burger_id }
# Expected: [{:id => 3, :name => "big mac"},{:id => 4, :name => "angus beef"}]
end

最佳答案

你已经很接近了,为了简单起见,我将所有“吃掉的”id 放入一个数组中,并检查是否包含在该数组中,如下所示:

BURGERS = [
{:id => 1, :name => "cheese burger"},
{:id => 2, :name => "royale"},
{:id => 3, :name => "big mac"},
{:id => 4, :name => "angus beef"}
]

EATEN = [
{:burger_id => 1},
{:burger_id => 2}
]

def burgers_not_eaten
eaten_ids = EATEN.map { |e| e[:burger_id] }
BURGERS.reject { |burger| eaten_ids.include?(burger[:id]) }
end

burgers_not_eaten
# => [{:id=>3, :name=>"big mac"}, {:id=>4, :name=>"angus beef"}]

关于ruby - 比较两个哈希数组并返回新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27828632/

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