Circular Array In ruby

The main logic behind this post says that “How do we move through the array indices in a circular manner” i.e whenever we reach the last index the control should be transferred back to the first index and vice versa. I actally means to say the array should navigate like a circular linked list.

So,The example below will clarify its usage and the logic behind it.

In my case,  I had a query getting some values for me in an array.The task was to paginate the array based on each values or index of the array one at a time.i had tried wot the standard paginator bulit into ruby but it provided me with a little freaky control over the array for circular pagination.So i decide to write some own logic of mine for a for this particular pagination.

The below code tells us the story for having a circular pagination.

The line 1 is nothing but the method get person details which takes the parameter as the current user id which is displayed on the page.

The line 2 is the query whcih gets the data for me for the pagination purpose.

 In the line 3  I am initalizing a new array

The do loops extracts all the Ids present in the array and pushes those ids into the array @o_ids.

 Now, what the return does is, it takes the its takes in the parameter id  of the current user being displayed and first finds the index of that particular id in the array and then decrements the index by 1 to get the value previous to that index and finally resolves the values at the index using the at instance method of the Array class. The second values returned is nothing but the postion of the actual id coming as a parameter, and the third return values is the value next to the current id.In the third case I check that the incremented Id does not exceed the length which will inturn throw a nil error while pagination.So using the ternary operator it evaluate the id back to zero index whenver it exceeds the last index of the array making the array circular

For Example:

Imagine that the array @o_ids has the following values and the id of the current user that is been shown is 103 so the get_person_details get 103 as the parameter. The line 21 shows the output which is 102(id decremented from the current Id), the 103(current Id) and 104(the incremented Id)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone