Apr 14 Sorting arrays of any object in Ruby

tags: arrays sorting | comments

Today I needed in my test units to assert whether arrays of Active Records objects were equal or not. That requires me to sort the arrays, since order is important when checking for equality of arrays.

Blocks in Ruby are really powerfull, and passing one to the Array sort! method is the key to sorting with the condition you want, in this case by the AR object id. Also notice the use of the <=> operator, the one used to compare elements, you only need the elements to have it, and Fixnum does.

class Array
  def sort_by_id
    sort! { |a,b| a.id <=> b.id }

with that in your test_helper.rb you can then assert:

assert_equal array_of_ARs.sort_by_id, will_paginate_result.to_a.sort_by_id

of course you can even make it more general, but for the moment I need this only :-)

credits go to ariejan’s blog for clearing the way.

blog comments powered by Disqus