Skip to content

Instantly share code, notes, and snippets.

@yaauie
Created April 9, 2013 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaauie/5348183 to your computer and use it in GitHub Desktop.
Save yaauie/5348183 to your computer and use it in GitHub Desktop.
require_relative 'range-split'
(1...1000).split(3) #=> [1...334, 334...667, 667...1000]
(1..1000).split(3) #=> [1...335, 335...669, 669..1000]
class Range
def split(split_qty)
raise ArgumentError, 'infity not supported' unless (
[self.begin,self.end] & [Float::INFINITY,-Float::INFINITY]
).empty?
chunk_size = Rational(self.count, split_qty).ceil
splits = self.each_slice(chunk_size).reduce([]) do |memo,split|
memo << (split.first...split.last.next)
end
last_split = splits.pop
splits << Range.new(last_split.begin, self.end, self.exclude_end?)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment