danynl
danynl

Reputation: 299

get element in array based on element's attributes

I have a simple question regarding how to extract elements from array based on their attribute(s).

I have an array of objects :

obj_array = [obj1,obj2,obj3........]

each objects has an attribute called 'type' which returns an object. So,

object1.type = type1
object2.type = type3
object3.type = type8
object4.type = type1
...

I would like to find and extract a list of objects in obj_array that is typed by 'type1' and store them in an array. The resulting array should look like this:

type1_array = [object1,object4]

Here is my solution using a loop:

type1_array = []
obj_array.each do |e|
   if e.type == type1
      type1_array << e
   end
end

Is there a short way to do this in Ruby without having to loop through every elements in the array?

Upvotes: 2

Views: 275

Answers (1)

larz
larz

Reputation: 5766

Ruby's selected method is probably what you're looking for.

obj_array.select { |obj| obj.type == type1 }

Obviously make sure you define type1.

Upvotes: 2

Related Questions