Class: TrailGuide::Algorithms::Weighted

Inherits:
Object
  • Object
show all
Defined in:
lib/trail_guide/algorithms/weighted.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(experiment) ⇒ Weighted

Returns a new instance of Weighted.



10
11
12
# File 'lib/trail_guide/algorithms/weighted.rb', line 10

def initialize(experiment)
  @experiment = experiment
end

Instance Attribute Details

#experimentObject (readonly)

Returns the value of attribute experiment.



4
5
6
# File 'lib/trail_guide/algorithms/weighted.rb', line 4

def experiment
  @experiment
end

Class Method Details

.choose!(experiment, **opts) ⇒ Object



6
7
8
# File 'lib/trail_guide/algorithms/weighted.rb', line 6

def self.choose!(experiment, **opts)
  new(experiment).choose!(**opts)
end

Instance Method Details

#choose!(**opts) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/trail_guide/algorithms/weighted.rb', line 14

def choose!(**opts)
  weights   = experiment.variants.map(&:weight)
  reference = rand * weights.inject(:+)

  experiment.variants.zip(weights).each do |variant,weight|
    return variant if weight >= reference
    reference -= weight
  end
end