开发者

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

开发者 https://www.devze.com 2023-03-28 04:02 出处:网络
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.

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开发者_如何学JAVA:

[
    [#<User id: 1, email: "abc@abc.com", username: "abc">, true],
    [#<User id: 2, email: "ijk@ijk.com", username: "ijk">, true],
    [#<User id: 3, email: "xyz@xyz.com", 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: "ijk@ijk.com", username: "ijk">, true]

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


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消