user3437721
user3437721

Reputation: 2289

Comparing a constant array with object array

I have a collection of objects with certain attributes. I also have a CONSTANT array of ids.

I want to return the whole objects who have an id that exists in the constant array.

This is what I have so far, but it just returns true or false for each, I need it to return an array of all the objects:

some_object_attributes.collect { |attr| (Constant::SOME_IDS.include? attr.object.object_type_id)}

How can I return every attr.object which has an ID in the constant array?

Upvotes: 0

Views: 153

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity, for a really huge array that way it might be faster:

some_object_attributes.group_by do |attr|
  attr.object.object_type_id
end.values_at(*Constant::SOME_IDS).flatten

This is O(N) because it does not look up the Constant::SOME_IDS array for each element.

Upvotes: 3

coreyward
coreyward

Reputation: 80041

You don't want to do a collect (aka map), which returns the result of the block. You want to return the object in the collection based on the result of the block. For that, there's select:

some_object_attributes.select do |attr| 
  Constant::SOME_IDS.include? attr.object.object_type_id
end

Upvotes: 3

jvillian
jvillian

Reputation: 20263

Use select instead of collect.

collect is returning the result of the evaluation (true or false). select will return the objects.

This article may be of use.

Upvotes: 0

Related Questions