Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on Rails 3.0. I have a two dimensional array. The two dimensional array consists of user data and a boolean value.

For example: [ [user1,true], [user2,true], [user3,false] ]

It looks something like this:

[
    [#<User id: 1, email: "[email protected]", username: "abc">, true],
    [#<User id: 2, email: "[email protected]", username: "ijk">, true],
    [#<User id: 3, email: "[email protected]", username: "xyz">, false],
]

I want to find/extract records conditionally; say finding an entire row where User id=2, it should return only the second row i.e. [#<User id: 2, email: "[email protected]", username: "ijk">, true]

Is there anyway to loop through such arrays? How can it be achieved?

like image 280
Bongs Avatar asked Aug 16 '11 07:08

Bongs


1 Answers

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 }
like image 60
fl00r Avatar answered Nov 16 '22 03:11

fl00r