Sorting Array of Objects using Ruby and Python

From my previous post, I had explained on how to sort an array consists of objects by object’s attribute using PHP. While on PHP sorting by object’s attribute requires additional function other than sorting itself, Ruby and Python has it’s own array of object sorting syntax.

For example in Ruby, the following one line syntax will sort an array named population by comparing it’s objects length property (attribute) ascendingly without additional sorting function like in PHP.

population.sort! {|a,b| a.length <=> b.length}

a more simple syntax applies to Python:

population.sort()

Python will look an object’s attribute in which data type is integer inside an array. So from python syntax above will sort every objects inside population array by object’s integer attribute value. Using above python sort function may or may not behave correctly to your needs. Python uses the same sorting techniques in sorting array of objects based on object’s attributes using a custom sorting function as sort function parameter.

def psort(self,a,b):
 if(a.length > b.length):
 return 1
 elif(a.length == b.length):
 return 0
 else:
 return -1
population.sort(psort)