Ruby Array Sorting
Join the DZone community and get the full member experience.Join For Free
Ever get a scenario where you have a sorted array of values (say ids) for objects that are in another unsorted array? This happens when you query SQL and retrieve a list of ids and the use WHERE id IN (.....). The second query loses the ordering. Heres a wrapper function for taking care of this:
# 'array' is the unsorted set of objects # 'att_sym' is the symbol of the attribute each object in array, that is represented in index_array # 'index_array' is the ordered array of values def sort_with_index(array, att_sym, index_array) return array.sort do |a, b| index_array.index(a.send(att_sym)).to_i <=> index_array.index(b.send(att_sym)).to_i end endThis could easily be modified to treat 'array' as self and use it as an extension of the array class.
Data structure Sorting
Opinions expressed by DZone contributors are their own.