Reputation: 2289
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
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
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