Off the Grid
Greg Osuri

I'm a hacker and an early stage investor interested in solving common problems in the simplest way possible.


I'm also the creator of Sociaholic.com - A better way to post tweets to your facebook

   

Search

April 14th, 7:10pm 4 comments

Sort on any attribute for objects stored in an array using Ruby Metaprogramming

Update 1: You could use array.sort_by{|obj| block } to achieve the same functionality. Read further if you are interested in learning more about Metaprogramming. (Thanks to knowtheory)

Ruby Metaprogramming is incredibly powerful, there are lots of good material and books but most of them i came across lack practical examples. One problem I was trying to solve is to perform a Bubble sort on objects stored in Array on their attributes, I believe this is a very common problem and I was able to do it with ease using almighty META.

I strongly advise watching the video by Dave Thomas and understand Ruby Object model before reading further.

The Problem

I have 6 objects of Person type in an sporadically created Array, each of them have 2 attributes - Name and Line_no. We want to sort the array based on Person's line number.

Solution 

We decided to use Bubble sort, mainly because its a simple to understand and we want any object to be able to use this function with out much modification. For simplicity purposes, I'm sorting ascending only on Integers, also assuming all the objects in the array are of same type.

First thing, is extending the Array to house our method "sort_by_attrib!"



class Array 
  def sort_by_attrib!(attrib)
     ....
  end 
end


If you notice closely in the code below, the ruby "self" is used at multiple instances, while self can change depending on where its called. It always represents the current/default object.

Also notice the send method which lets you call a method on the object. In our case self[i].send("#{attrib}") will return the value of the instance variable name that has the value of attrib, in our case it returns "line_no". The rest is pretty much the logic to do a bubble sort.

Full Code:

Hope you enjoyed the article, I greatly appreciate your feedback and thought. Please subscribe and follow me on twitter for more incredible updates.