比较两个哈希数组和 return 新对象

Compare two arrays of hashes and return new object

我有两个哈希数组。

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}
          ]

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

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

你很接近,为了简单起见,我将所有 "eaten" 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"}]