Skip to content

Instantly share code, notes, and snippets.

@teeparham
Created February 8, 2013 04:24
Show Gist options
  • Save teeparham/4736578 to your computer and use it in GitHub Desktop.
Save teeparham/4736578 to your computer and use it in GitHub Desktop.
ruby array extension that combines ActiveSupport in_groups_of + each_with_index
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