Module: MadderLib::Conditional::Likely::Instruction
- Included in:
- Instruction
- Defined in:
- lib/madderlib/conditional/likely.rb
Overview
Likely::Instruction
Introduces support for proportional selection from multiple Instructions in a given Phrase
See: Likely::Phrase
Class Method Summary collapse
-
.included(target) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#conditional_likely_tester ⇒ Object
:nodoc:.
-
#likely(*args, &block) ⇒ Object
(also: #weight, #weighted, #weighing, #odds)
Specifies the likelihood of this Instruction being used, compared to its siblings in their Phrase.
Class Method Details
.included(target) ⇒ Object
:nodoc:
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/madderlib/conditional/likely.rb', line 83 def self.included(target) #:nodoc: # register a test to test all allowances for the instruction # return false at the first one that fails target.add_test do |instruction, context| phrase = instruction.phrase test = true state = context.state(phrase) total = state[:likely_total] count = state[:likely_count] # will only have a count if there's likelihood calc required if count state = context.state(instruction) lower = state[:likely_lower] upper = state[:likely_upper] test = (count >= lower) && (count < upper) if test && phrase.respond_to?(:recurs?) && phrase.recurs? # set it up for the next recurrance # we don't want the same thing over and over again state[:likely_count] = rand(total) end end test end end |
Instance Method Details
#conditional_likely_tester ⇒ Object
:nodoc:
155 156 157 |
# File 'lib/madderlib/conditional/likely.rb', line 155 def conditional_likely_tester #:nodoc: @likely_tester end |
#likely(*args, &block) ⇒ Object Also known as: weight, weighted, weighing, odds
Specifies the likelihood of this Instruction being used, compared to its siblings in their Phrase
If provided, the arguments should contain:
-
a numeric value, which becomes the weight
-
a Range, or two numerics (which define a Range), from which the weight is chosen randomly
-
a Proc / lambda / block / closure, which returns a numeric value. \
The block can either take no arguments, or a Context.
See: Instruction#alternately
Examples:
builder = madderlib do
say('parsley').likely(4)
alternately(3).say('sage')
alternately.say('rosemary').weighted(2).or.say('thyme')
end
usage = {}
60.times do
key = builder.sentence
usage[key] = (usage[key] || 0) + 1
end
# if proportions were accurately reproducible:
# usage['parsley'].should eql(20)
# usage['sage'].should eql(15)
# usage['rosemary'].should eql(10)
# usage['thyme'].should eql(5)
143 144 145 146 147 |
# File 'lib/madderlib/conditional/likely.rb', line 143 def likely(*args, &block) # build a tester, set it aside @likely_tester = Helper::TestBlock.new *args, &block self end |