Module: Tins::Minimize
- Included in:
- Array
- Defined in:
- lib/tins/minimize.rb
Overview
Tins::Minimize provides methods for compressing sequential data into ranges and expanding ranges back into individual elements.
This module is designed for objects that respond to [] and size methods, such as Array, and whose elements respond to the succ method (like String and Numeric types). It’s particularly useful for representing sequential data more compactly and efficiently.
Instance Method Summary collapse
-
#minimize ⇒ Array<Range>
Returns a minimized version of this object, that is successive elements are substituted with ranges a..b.
-
#minimize! ⇒ Object
First minimizes this object, then calls the replace method with the result.
-
#unminimize ⇒ Array
Invert a minimized version of an object.
-
#unminimize! ⇒ Object
Invert a minimized version of this object in place.
Instance Method Details
#minimize ⇒ Array<Range>
Returns a minimized version of this object, that is successive elements are substituted with ranges a..b. In the situation …, x, y,… and y != x.succ a range x..x is created, to make it easier to iterate over all the ranges in one run.
39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/tins/minimize.rb', line 39 def minimize result = [] last_index = size - 1 size.times do |i| result << [ self[0] ] if i == 0 if self[i].succ != self[i + 1] or i == last_index result[-1] << self[i] result << [ self[i + 1] ] unless i == last_index end end result.map! { |a, b| a..b } end |
#minimize! ⇒ Object
First minimizes this object, then calls the replace method with the result.
56 57 58 |
# File 'lib/tins/minimize.rb', line 56 def minimize! replace minimize end |
#unminimize ⇒ Array
Invert a minimized version of an object. Some small examples:
[ 'A'..'C', 'G'..'G', 'K'..'M' ].unminimize # => [ 'A', 'B', 'C', 'G', 'K', 'L', 'M' ]
and
[ 1..2, 4..5 ].unminimize # => [ 1, 2, 4, 5 ]
66 67 68 69 70 71 72 73 74 |
# File 'lib/tins/minimize.rb', line 66 def unminimize result = [] for range in self for e in range result << e end end result end |
#unminimize! ⇒ Object
Invert a minimized version of this object in place.
79 80 81 |
# File 'lib/tins/minimize.rb', line 79 def unminimize! replace unminimize end |