DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Ruby Array Sorting
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
end
This could easily be modified to treat 'array' as self and use it as an extension of the array class.






Comments
Snippets Manager replied on Mon, 2007/08/27 - 6:52pm
class Array def sort_with_index(att_sym, index_array) self.sort_by {|el| index_array.index( el.send(att_sym) ) } end end