Class: Hegel::Generators::SampledFromGenerator

Inherits:
Hegel::Generator show all
Defined in:
lib/hegel/generators.rb,
sig/hegel.rbs

Overview

Hegel::Syntax::Methods#sampled_from. One element of collection, picked by drawing an index in [0, collection.size - 1].

Instance Method Summary collapse

Methods inherited from Hegel::Generator

#filter, #map

Constructor Details

#initialize(collection) ⇒ SampledFromGenerator

Returns a new instance of SampledFromGenerator.

Parameters:

  • collection (Object)


208
209
210
211
# File 'lib/hegel/generators.rb', line 208

def initialize(collection)
  super()
  @collection = collection
end

Instance Method Details

#do_draw(tc) ⇒ Object

Parameters:

  • tc (Object)

Returns:

  • (Object)

Raises:



213
214
215
216
217
218
219
220
221
222
223
# File 'lib/hegel/generators.rb', line 213

def do_draw(tc)
  raise Hegel::Error, "sampled_from: collection must not be empty" if @collection.empty?

  tc.start_span(LibHegel::HEGEL_LABEL_SAMPLED_FROM)
  begin
    index = tc.generate_integer(0, @collection.size - 1)
    @collection.to_a[index]
  ensure
    tc.stop_span(discard: false)
  end
end