Sha256: a88baa2519a4f7fab7f52e7ef3c904360b89cbd670378d2b87889cbe48301e5b

Contents?: true

Size: 823 Bytes

Versions: 2

Compression:

Stored size: 823 Bytes

Contents

class RangeBuilder

  # Usage:
  #  build_range( persons ){|person| person.age  }
  def self.build_range enum
    first, last = nil, nil
    comp_first, comp_last = nil, nil
    enum.each do |obj|
      comp = yield obj
      if first == nil || comp < comp_first
        first = obj
        comp_first = yield first
      end
      if last  == nil || comp > comp_last
        last  = obj
        comp_last = yield last
      end
    end
    [first, last]
  end

  # arg: sorted enum. elements must implement succ
  def self.build_from_sorted enum
    ranges = []
    return ranges if enum.empty?
    first = last = enum.first
    enum.each_cons(2) do |a,b|
      last = b
      if a.succ != b
        ranges << Range.new(first,a)
        first = b
      end
    end
    ranges << Range.new(first,last)
    ranges
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
range_builder-1.0.2 lib/range_builder.rb
range_builder-1.0.1 lib/range_builder.rb