13

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?

2
  • It is a simple loop; what have you tried so far? As an aside, do you want to do this only with an in-memory array or is your goal to be efficient and load only that record from the database? Commented Aug 16, 2011 at 8:11
  • it should efficiently fetch only one record.. I'm checking the following solutions... Commented Aug 17, 2011 at 5:26

3 Answers 3

23
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 }
Sign up to request clarification or add additional context in comments.

2 Comments

I'm new to this, but surprisingly when I tried first command @m.select{ |user, flag| user.id == 2} it returned all the three records. So instead of select I used detect and it worked. The other two commands @m.select{ |user, flag| flag } and @m.select{ |user, flag| !flag } worked very well. Thanks...
looks like you try @m.select{ |user, flag| user.id = 2} or all off them are with ID=2
11

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.

1 Comment

@m.select{ |u| u.first.id == 2 } returning all the records. But when I changed it to @m.detect{ |u| u.first.id == 2 } it returned only one record. I'm new to it. Can you tell me why it is so?
9

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.