Method: PropCheck::Generators.array
- Defined in:
- lib/prop_check/generators.rb
.array(element_generator, min: 0, max: nil, empty: true, uniq: false) ⇒ Object
Generates an array of elements, where each of the elements is generated by element_generator.
Shrinks to shorter arrays (with shrunken elements). Accepted keyword arguments:
empty: When false, behaves the same as ‘min: 1` min: Ensures at least this many elements are generated. (default: 0) max: Ensures at most this many elements are generated. When nil, an arbitrary count is used instead. (default: nil) uniq: When true, ensures that all elements in the array are unique.
When given a proc, uses the result of this proc to check for uniqueness.
(matching the behaviour of `Array#uniq`)
If it is not possible to generate another unique value after the configured `max_consecutive_attempts`
an `PropCheck::Errors::GeneratorExhaustedError` will be raised.
(default: `false`)
>> Generators.array(Generators.positive_integer).sample(5, size: 1, rng: Random.new(42))
=> [[2], [2], [2], [1], [2]]
>> Generators.array(Generators.positive_integer).sample(5, size: 10, rng: Random.new(42))
=> [[10, 5, 1, 4], [5, 9, 1, 1, 11, 8, 4, 9, 11, 10], [6], [11, 11, 2, 2, 7, 2, 6, 5, 5], [2, 10, 9, 7, 9, 5, 11, 3]]
>> Generators.array(Generators.positive_integer, empty: true).sample(5, size: 1, rng: Random.new(1))
=> [[], [2], [], [], [2]]
>> Generators.array(Generators.positive_integer, empty: false).sample(5, size: 1, rng: Random.new(1))
=> [[2], [1], [2], [1], [1]]
>> Generators.array(Generators.boolean, uniq: true).sample(5, rng: Random.new(1))
=> [[true, false], [false, true], [true, false], [false, true], [false, true]]
376 377 378 379 380 381 382 383 384 385 |
# File 'lib/prop_check/generators.rb', line 376 def array(element_generator, min: 0, max: nil, empty: true, uniq: false) min = 1 if min.zero? && !empty uniq = proc { |x| x } if uniq == true if max.nil? nonnegative_integer.bind { |count| make_array(element_generator, min, count, uniq) } else choose(min..max).bind { |count| make_array(element_generator, min, count, uniq) } end end |