Godzilla74 Godzilla74 - 7 months ago 11
Ruby Question

Ruby Iterate over two arrays and delete matching values

I'm trying to iterate over 2 arrays in my Ruby on Rails Program and create a new array with the Objects that shouldn't be excluded, however, I'm stumped.

Here is my Object array that I need to iterate over to check:

=> [#<Result id: 1437, network_host_test_id: 1320, issue_id: 50231, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-27 18:08:00", deleted_at: nil>,
#<Result id: 1438, network_host_test_id: 1320, issue_id: 47573, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>,
#<Result id: 1439, network_host_test_id: 1320, issue_id: 39758, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>,
#<Result id: 1441, network_host_test_id: 1320, issue_id: 47574, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>,
#<Result id: 1442, network_host_test_id: 1320, issue_id: 50442, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>,
#<Result id: 1443, network_host_test_id: 1320, issue_id: 40991, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>,
#<Result id: 1444, network_host_test_id: 1320, issue_id: 43896, created_at: "2016-04-14 19:30:22", updated_at: "2016-04-14 19:30:22", deleted_at: nil>]


My exclude array:

[#<DeferredIssue id: 1, defer_reason: "Test for issue", defer_name: "JF", issue_id: 50231, created_at: "2016-04-28 17:50:37", updated_at: "2016-04-28 17:50:37", network_host_id: 76>,
#<DeferredIssue id: 2, defer_reason: "Defer a 10", defer_name: "Travis", issue_id: 43896, created_at: "2016-04-28 17:51:25", updated_at: "2016-04-28 17:51:25", network_host_id: 76>]


So, in the end, my actual array should not have Objects with the
issue_id
of
50231
or
43896
.

I tested this out initially using the
.exclude?
method, but my exclude array was just
[50231, 43896]
. Now that they are objects, that type of iteration doesn't work.

What is the Ruby way to do this type of thing?

Answer

You can transform your array to array of issue_ids with map:

ids = exclude_array.map(&:issue_id)
#=> [50231, 43896]
your_objects.select {|o| ids.exclude?(o.issue_id) }