1

My question is very simple, I have:

@users = User.first(100)

From the @users array, how can i get the user object with the id 50?

3 Answers 3

3

Use detect:

user = @users.detect { |u| u.id == 50 }

Though there are ways to fetch just one record (with id 50) if you don't need the remaining 99.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, do you think your answer is better? I've never read about detect.
You should check the link to its documentation. I don't know about @users.find, how it works. But detect will iterate over the @users and when first element with matching condition is found, loop breaks and that element is returned.
2

If you want to do an ActiveRecord find you can do:

@users = User.find_by_id(50)

Or if you want to do an Array find you can do:

@users.find_all { |user| user.id == 50 }

1 Comment

Thanks for your answer, is very close of how I get it. Do you think your answer is better?
2

I have found a solution myself, but I'll wait until other people tell us which answer is better.

@users.find {|u| u.id == 50 }

Thanks for your answers!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.