Posted By

gdonald on 09/27/06


Tagged

array chop


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


ruby array chop


 / Published in: Ruby
 

  1. # for creating sets of data for tables generally. it enables you to
  2. # take an array and create sections with it.
  3. #
  4. # a = [1,2,3,4,5,6,7,8,9,10]
  5. # b = array_chop(a,3)
  6. # b.inspect
  7. # "[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]"
  8.  
  9. def array_chop( data, num )
  10. res = Array.new
  11. buf = data.to_a.reverse
  12. ( data.size / num ).times do |row|
  13. tmp = Array.new
  14. num.times do |col|
  15. tmp << buf.pop
  16. end
  17. res << tmp
  18. end
  19. res << buf unless buf.size == 0
  20. res
  21. end

Report this snippet  

You need to login to post a comment.