Skip to content

Instantly share code, notes, and snippets.

@nelstrom
Created April 8, 2009 11:06
Show Gist options
  • Save nelstrom/91723 to your computer and use it in GitHub Desktop.
Save nelstrom/91723 to your computer and use it in GitHub Desktop.
class Array
# If you want the first n items from an array, you could call first(n)
# but if the array has less than n members, so will the return value.
# This method ensures that the return value has as many items as requested,
# by cycling through the array from the beginning.
# e.g. [1,2,3].modulo(2) => [1,2]
# [1,2,3].modulo(4) => [1,2,3,1]
# [1,2,3].modulo(7) => [1,2,3,1,2,3,1]
def modulo(required_size)
required_size = size if required_size.nil?
if required_size <= size
first(required_size)
else
multiplier = required_size / size
oversized = self * (multiplier + 1)
oversized.first(required_size)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment