Created
February 8, 2013 04:24
-
-
Save teeparham/4736578 to your computer and use it in GitHub Desktop.
ruby array extension that combines ActiveSupport in_groups_of + each_with_index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
# [1,2,3,4,5,6,7,8].in_groups_of_with_index(3, false) do |group, index| | |
# puts group.to_s + " " + index.to_s | |
# end | |
# [1, 2, 3] 0 | |
# [4, 5, 6] 1 | |
# [7, 8] 2 | |
# => [[1, 2, 3], [4, 5, 6], [7, 8]] | |
# | |
# [1,2,3,4,5,6,7,8].in_groups_of_with_index(3, "x") do |group, index| | |
# puts group.to_s + " " + index.to_s | |
# end | |
# [1, 2, 3] 0 | |
# [4, 5, 6] 1 | |
# [7, 8, "x"] 2 | |
# => [[1, 2, 3], [4, 5, 6], [7, 8, "x"]] | |
def in_groups_of_with_index(number, fill_with = nil) | |
i = 0 | |
in_groups_of(number, fill_with).each do |group| | |
yield group, i | |
i = i + 1 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment