Search code examples
ruby-on-railsrubyarrayshashenumerable

I would like to know the best way to implement the following


I have a collection of User data, and I want to get the first_name all those users. We can simply use

user_list.map(&:first_name)

similarly for middle and last name, I need to do the same

user_list.map(&:middle_name)
user_list.map(&:last_name)

as we can see here I have to loop over the same data 3 times to get collection of first, middle and last name. Can anyone suggest me a way I can do that in a single loop.

so the output will be like.

{first_name: ["tom", "harry", "ronald"], middle_name: ["marvello", "james", "bilius"], last_name: ["riddle", "potter", "weasley"] }

PS, its not an active record call to use pluck. Its a collection of record on which i need to run this, not a Active record call.


Solution

  • An obvious solution is an each loop:

    names = {first_name: [], middle_name: [], last_name: []}    
    user_list.each do |user|
      names[:first_name] << user.first_name
      names[:middle_name] << user.middle_name
      names[:last_name] << user.last_name
    end
    

    Or using each_with_object:

    user_list.each_with_object(first_name: [], middle_name: [], last_name: []) do |user, names|
      names[:first_name] << user.first_name
      names[:middle_name] << user.middle_name
      names[:last_name] << user.last_name
    end