Sha256: 4666ecbd4ee3980c8727b31cdc83f627f8296c7ba9ffd4a5c628a7c7832a9d99

Contents?: true

Size: 1.67 KB

Versions: 8

Compression:

Stored size: 1.67 KB

Contents

module Mext

  #
  # +Mext::CompressedArray+
  #
  # is an +array+ in which values are expanded according to the following
  # format: if a value is a 2-place array it is interpreted as:
  # +[value, num_of_repetitions]+. The array is actually expanded during
  # creation so there is currently no way to retrieve the original format.
  #
  class CompressedArray < Array

    #
    # +Mext::CompressedArray.new(me = [])+
    #
    # create a array with a special array whose format accept the following
    # values:
    # * single values (go untreated)
    # * arrays of two values (interpreted as +[value, num_of_repetitions]+ -
    #   +num_of_repetitions+ value is checked to be a +Fixnum+ to expand
    #   +value+ for +num_of_repetitions+ (otherwise the array is passed unprocessed)
    # * anything else is passed unprocessed
    #
    def initialize(me = [])
      new_array = expand(me)
      self.replace(new_array)
    end

    class << self

      #
      # +from_yaml(hash)+
      #
      # create from a +yaml+ +Hash+ configuration
      #
      def from_yaml(ha)
        raise ArgumentError unless ha.kind_of?(Hash) && ha.has_key?('args')
        args = ha['args']
        new(args)
      end

    end

  private

    def expand(a)
      res = []
      a.each do
        |val|
        if expand_value?(val)
          ex_val = expand_value(val)
          res.concat(ex_val)
        else
          res << val
        end
      end
      res
    end

    def expand_value?(val)
      val.kind_of?(Array) && (val.size == 2) && val[1].is_a?(Integer)
    end

    def expand_value(val)
      res = []
      value = val[0]
      0.upto(val[1]-1) { |n| res << value }
      res
    end

  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
ruby-mext-0.21.6 lib/mext/array/compressed_array.rb
ruby-mext-0.21.5 lib/mext/array/compressed_array.rb
ruby-mext-0.21.4 lib/mext/array/compressed_array.rb
ruby-mext-0.21.3 lib/mext/array/compressed_array.rb
ruby-mext-0.21.2 lib/mext/array/compressed_array.rb
ruby-mext-0.21.1 lib/mext/array/compressed_array.rb
ruby-mext-0.21.0 lib/mext/array/compressed_array.rb
ruby-mext-0.20.1 lib/mext/array/compressed_array.rb