Class: Randomer::Percent
- Inherits:
-
Object
- Object
- Randomer::Percent
- Defined in:
- lib/randomer.rb
Class Method Summary collapse
-
.pick_one(hash) ⇒ Object
根据一个hash中value指定的权重随机获取一个Symbol或String.
- .pick_some(hash, count, mutex = true) ⇒ Object
Class Method Details
.pick_one(hash) ⇒ Object
根据一个hash中value指定的权重随机获取一个Symbol或String
- params
-
Hash hash
- return
-
Symbol key
- usage
-
Randomer::Percent.pick_one(
:a => 60, :b => 400,)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/randomer.rb', line 76 def pick_one(hash) sum_value = 0 interval = [] keys = [] hash.each do |key, value| return false unless key.is_a? Symbol or key.is_a? String or key.is_a? Integer return false unless value.is_a? Integer interval << (sum_value...(sum_value += value)) keys << key end return false if sum_value <= 0 count = interval.count rand_result = rand sum_value interval.each_with_index do |range, index| return keys[index] if range.include? rand_result end end |
.pick_some(hash, count, mutex = true) ⇒ Object
96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/randomer.rb', line 96 def pick_some(hash, count, mutex = true) hash = hash.clone _some = [] count.times do key = self.pick_one hash next if not key _some << key hash.delete key if mutex end _some end |