Sha256: 0018be5b97742c07ae5da23222801b7d9d3439b7ef969c66e2c596a33e7decaf

Contents?: true

Size: 1.24 KB

Versions: 7

Compression:

Stored size: 1.24 KB

Contents

module VGen
  class HashGen
    def initialize(
          with: {},
          min: 4,
          max: 8,
          length: nil,
          size: nil,
          key_gens:   [ proc {Random.new.rand(0..100)} ],
          value_gens: [ proc {Random.new.rand} ]
        )
      @with = with
      @length = length || size || (min..max)
      @key_gens = key_gens
      @value_gens = value_gens
      @min = min
      @max = max
    end
    
    def call()
      with_length = @with.length
      hash = Hash[
        Array.new(hash_length - with_length) do
          [
            @key_gens.sample.call,
            @value_gens.sample.call
          ]
        end
      ]
      unless @with.empty?
        hash.merge!(@with)
      end
      while hash.size < hash_length do
        new_pair =  {
          @key_gens.sample.call => @value_gens.sample.call
        }
        hash = new_pair.merge(hash)  
      end
      hash = hash.to_a.shuffle.to_h unless @with.empty?
      hash
    end

    private

    def hash_length
      length = Random.new.rand(@length) if @length.is_a? Range
      length = @length if @length.is_a? Integer
      raise "length (size) can't be negative" if length < 0
      length
    end
  end
end

Version data entries

7 entries across 5 versions & 2 rubygems

Version Path
bsielski_control_flow-1.0.0 vendor/bundle/ruby/2.5.0/gems/bsielski_value_generator-1.2.0/lib/bsielski_v_gen/hash_gen.rb
bsielski_control_flow-1.0.0 vendor/bundle/ruby/2.5.0/gems/bsielski_value_generator-1.4.0/lib/v_gen/hash_gen.rb
bsielski_control_flow-1.0.0 vendor/bundle/ruby/2.5.0/gems/bsielski_value_generator-1.3.0/lib/v_gen/hash_gen.rb
bsielski_value_generator-1.4.0 lib/v_gen/hash_gen.rb
bsielski_value_generator-1.3.0 lib/v_gen/hash_gen.rb
bsielski_value_generator-1.2.0 lib/bsielski_v_gen/hash_gen.rb
bsielski_value_generator-1.1.0 lib/bsielski_v_gen/hash_gen.rb