Sha256: 56d24efd56b3df8c44aa2a953027d5d10fe4d968646925aacabc7fdab451d166

Contents?: true

Size: 705 Bytes

Versions: 1

Compression:

Stored size: 705 Bytes

Contents

module Haversack
  class ItemCollection < Array

    def initialize(data, &block)
      if !block_given?
        raise ArgumentError, "expected #{data} to contain only elements of class Haversack::Item" unless data.is_a?(Array) && ItemCollection.only_items?(data)
      end

      @size   = self.size
      @weight = self.weight

      block_given? ? super(data, block) : super(data)
    end

    def size
      map(&:size).sum
    end

    def weight
      map(&:weight).sum
    end

    def push(obj)
      raise Haversack::KnapsackContentError unless obj.is_a? Haversack::Item
      super
    end

    def self.only_items?(data)
      data.all? { |el| el.is_a? Haversack::Item }
    end
    
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
haversack-1.0.0 lib/haversack/itemcollection.rb