How do I check between 2 arrays of different objects?
I want to check if a claim's items has assets in it and @item_assets basically gets all the items in the databas开发者_StackOverflow中文版e that are classified as assets.
When doing the following:
>> @claim.items
=> [#<Item id: 8, name: "chair", amount: 10.0, gst: 0.7, override: false, item_category_id: 7, item_expense_id: 8, claim_id: 8, club_id: 71, created_at: "2009-10-18 10:16:10", updated_at: "2009-10-18 10:16:10">, #<Item id: 9, name: "soemthing", amount: 20.0, gst: 1.4, override: false, item_category_id: 7, item_expense_id: 7, claim_id: 8, club_id: 71, created_at: "2009-10-18 10:16:10", updated_at: "2009-10-18 10:16:10">]
>> @items_assets
=> [#<Item id: 8, name: "chair", amount: 10.0, gst: 0.7, override: false, item_category_id: 7, item_expense_id: 8, claim_id: 8, club_id: 71, created_at: "2009-10-18 10:16:10", updated_at: "2009-10-18 10:16:10">, #<Item id: 9, name: "soemthing", amount: 20.0, gst: 1.4, override: false, item_category_id: 7, item_expense_id: 7, claim_id: 8, club_id: 71, created_at: "2009-10-18 10:16:10", updated_at: "2009-10-18 10:16:10">]
>> @claim.items.include? @items_assets
=> false
The result puzzles me. After investigation I realize that the items on both arrays are of different object even though they refer to the same id.
As such, it appears that include? can no longer work in this case.
Can someone suggest how else should I go about checking if a claim's items have assets in it?
Claim HM Items
Items BT Claim
@claim.items.include? @items_assets
What you're asking here is "Does the array @claim.items
contain an element equal to the @item_assets
object?"
What you seem to want to ask is "Does the array @claim.items
contain an element equal to any element in another array, @item_assets
?"
@claim.items != @claim.items - @item_assets
would return true if any element in @item_assets
matched any element in @claim.items
, but the performance of doing that will likely be terrible.
I would look at storing your @item_assets
in a Set
, assuming you really do want to yank them all into memory. Then checks to see if your @claim.items
elements appear in that Set
will be much faster.
精彩评论