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

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby Array Sorting

11.27.2008
| 6629 views |
  • submit to reddit
        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

Here is the suggestion, with the added change of using sort_by, which is much faster for anything large: class Array def sort_with_index(att_sym, index_array) self.sort_by {|el| index_array.index( el.send(att_sym) ) } end end