Thursday, February 23, 2012

Ruby: concept of paginating

 paginating an array

Proof of Concept:

Preparing dummy array :
test = []
1.9.2p290 :053 > (1..50).each do |g|
1.9.2p290 :054 > test += [g]
1.9.2p290 :055?> end
=> 1..50
1.9.2p290 :056 > test
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

We know that test[1..5] will return [1, 2, 3, 4, 5] of elements.

Function to get the item number by 5 item per page.

1.9.2p290 :061 > def item_number page
1.9.2p290 :062?> perpage = 5
1.9.2p290 :063?> margin = perpage * (page - 1)
1.9.2p290 :064?> start = margin + 1
1.9.2p290 :065?> ending = page * perpage
1.9.2p290 :066?> return start..ending
1.9.2p290 :067?> end

Using the function to get page number 4

1.9.2p290 :069 > test[item_number 4]
=> [17, 18, 19, 20, 21]

happy arraying!

1 comment:

  1. China has recently suffered a variety of embarrassments stemming from poisoned milk, lead in toys, as well as a slew of other top quality control difficulties in a variety of Chinese Dress items. Most lately automobile business leader Toyota

    ReplyDelete