Class: WeightedRandomizer
- Inherits:
-
Object
- Object
- WeightedRandomizer
- Defined in:
- lib/weighted_randomizer.rb
Overview
Note:
Mostly adapted from recipe 5.11 from the Ruby Cookbook.
Implements weighted randomization for a group of weighted items. This class expects a hash of key -> value pairs where the value is the weight for the item.
Constant Summary collapse
- VERSION =
'0.1.2'
Instance Method Summary collapse
-
#initialize(items) ⇒ WeightedRandomizer
constructor
Creates a new instance.
-
#sample(num = nil) ⇒ Object+
Returns one or more weighted random values.
Constructor Details
#initialize(items) ⇒ WeightedRandomizer
Creates a new instance.
17 18 19 |
# File 'lib/weighted_randomizer.rb', line 17 def initialize(items) @items = normalize(items) end |
Instance Method Details
#sample(num = nil) ⇒ Object+
Returns one or more weighted random values.
25 26 27 28 |
# File 'lib/weighted_randomizer.rb', line 25 def sample(num = nil) return _sample unless num Array.new(num) { _sample } end |