Bloomberg
Bloomberg

Reputation: 2367

How can I do something like this with ruby arrays

I have an user array like this:

users_array = [[1,text for 1],[2,text for 2],[3,text for 3],[4,text for 4],[5,text for 5]]

here first element is user_id and second element is text which is specific to user_id in the same array.

Now I am trying to have user object from instead of ids in array like these.

users_array = [[#<User id: 1, encrypted_email: "">,text for 1],[#<User id: 2, encrypted_email: "">,text for 2],[#<User id: 3, encrypted_email: "">,text for 3],[#<User id: 4, encrypted_email: "">,text for 4],[#<User id: 5, encrypted_email: "">,text for 5]]

I am trying not to loop the array and hit the db thousand times for thousands user.

Upvotes: 0

Views: 54

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52377

data = users_array.to_h
# find all users with single query and build your map
User.where(id: data.keys).map { |user| [user, data[user.id]] }

Upvotes: 4

Stefan
Stefan

Reputation: 114248

You could use transpose to extract ids and values, and zip to combine users and values:

ids, values = users_array.transpose
users_array = User.find(ids).zip(values)

Upvotes: 1

Related Questions