Class: Range
- Inherits:
-
Object
- Object
- Range
- Defined in:
- lib/range_slice.rb
Instance Method Summary collapse
-
#slice(increment) ⇒ Object
Slices the range into smaller ranges of a given increment.
Instance Method Details
#slice(increment) ⇒ Object
Slices the range into smaller ranges of a given increment.
(1..1000).slice(300)
# => [1..300, 301..600, 601..900, 901..1000]
require 'active_support'
(7.days.ago..Time.now).slice(24.hours)
# => [Thu Apr 10 17:48:08 -0700 2008..Fri Apr 11 17:48:07 -0700 2008,
Fri Apr 11 17:48:08 -0700 2008..Sat Apr 12 17:48:07 -0700 2008,
Sat Apr 12 17:48:08 -0700 2008..Sun Apr 13 17:48:07 -0700 2008,
Sun Apr 13 17:48:08 -0700 2008..Mon Apr 14 17:48:07 -0700 2008,
Mon Apr 14 17:48:08 -0700 2008..Tue Apr 15 17:48:07 -0700 2008,
Tue Apr 15 17:48:08 -0700 2008..Wed Apr 16 17:48:07 -0700 2008,
Wed Apr 16 17:48:08 -0700 2008..Thu Apr 17 17:48:07 -0700 2008,
Thu Apr 17 17:48:08 -0700 2008..Thu Apr 17 17:48:08 -0700 2008]
Note: This method like most built-in range methods, doesn’t work with descending ranges (e.g., (1000..1).include? 2 returns false)
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/range_slice.rb', line 25 def slice(increment) start_values = [first] while self.include?(next_value = start_values.last + increment) start_values << next_value end end_values = [] start_values.each do |start_value| end_value = start_value + increment - 1 unless self.include? end_value end_value = self.last end end_values << end_value end result = [] start_values.each_with_index do |start_value, index| end_value = end_values[index] result << (start_value..end_value) end result end |