How to find record from an array of two dimensional array in rails 3? How to find record from an array of two dimensional array in rails 3? ruby ruby

How to find record from an array of two dimensional array in rails 3?


my_array.select{ |user, flag| user.id == 2}

all users with true flag:

my_array.select{ |user, flag| flag }

or false:

my_array.select{ |user, flag| !flag }


You can do something like

[ [user1,true], [user2,true], [user3,false] ].select { |u| u.first.id == 2}

This will return only the records that have the user id equal to 2.


Same answer as @eugen, only syntax difference(and using detect to return single dimensional array instead of 2 dimensional array):

[ [user1,true], [user2,true], [user3,false] ].detect { |user, boolean| user.id == 2 }=> [user2, true]