Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created January 18, 2019 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/c023b780886ff872d7895d998a0c9611 to your computer and use it in GitHub Desktop.
Save baweaver/c023b780886ff872d7895d998a0c9611 to your computer and use it in GitHub Desktop.
user_id_tp = tutor_profiles.index_by(&:user_id)
tutor_subjects = TutorSubject
.where(tutor_id: user_id_tp.keys)
.group_by(&:tutor_id)
.to_h { |uid, subjects| [user_id_tp[uid], subjects.map(&:subject_id)] }
# Faster
user_id_tp = tutor_profiles.index_by(&:user_id)
hash_of_arrays = Hash.new { |h,k| [] }
tutor_subjects = TutorSubject
.where(tutor_id: user_id_tp.keys)
.each_with_object(hash_of_arrays) do |subject, subjects|
subjects[subject.tutor_id].push(subject.id)
end
# Fastest
user_id_tp = tutor_profiles.index_by(&:user_id)
tutor_subjects = TutorSubject
.where(tutor_id: user_id_tp.keys)
.pluck('tutor_id', 'subject_id')
.each_with_object(hash_of_arrays) { |(tid, sid), subjects| h[tid] << sid }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment