ruby array chop


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.