Array divide method


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



Copy this code and paste it in your HTML
  1. # orginal article : http://blog.jayfields.com/2007/09/ruby-arraychunk.html
  2.  
  3. class Array
  4.  
  5. # divides an array into a smaller chunks
  6. # [1,2,3,4].divide_by 2 # => [[1,2],[3,4]]
  7. def divide_by(number_of_chunks)
  8. chunks = (1..number_of_chunks).collect { [] }
  9. self.each_with_index do |item, index|
  10. chunks[index % number_of_chunks] << item
  11. end
  12. chunks
  13. end
  14.  
  15. alias / divide_by
  16.  
  17. end
  18.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.