We can sort the array of integers in ruby easily, just by using the sort function. But what if we want to sort array of arrays or array of objects etc. For this we need some thing where we can provide our sorting conditions. Ruby provide this functionality using sort and sort_by functions.
Lets take a example of array of arrays:
Now you want to sort this array in the ascending order of the middle element of the inner arrays. All you need to do is:
Here x,y are the elements of arrays like ‘[1,4,3]’ (a element of array) and using x and y we are comparing the middle elements. Now lets look at opeartor <=> :
Now if you don’t want to use <=> operator then you can do this like:
Here you basically focus on the part of element using which you want to sort the whole array.comments powered by Disqus