Class: Keybox::Randomizer

Inherits:
Object
  • Object
show all
Defined in:
lib/keybox/randomizer.rb

Overview

Randomizer will randomly pick a value from anything that behaves like an array or has a to_a method. Behaving like an array means having a size or length method along with an at method.

The source of randomness is determined at runtime. Any class that can provide a rand method and operates in the same manner as Kernel#rand can be a used as the random source.

The item that is being ‘picked’ from can be any class that has a size method along with an at method.

array = ("aaa"..."zzz").to_a
r = Randomizer.new
r.pick_one_from(array)          # => "lho"
r.pick_count_from(array,5)      # => ["mvt", "tde", "wdu", "ker", "bgc"]

Constant Summary collapse

REQUIRED_METHODS =
%w( at size )

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(random_source_klass = ::Keybox::RandomSource) ⇒ Randomizer

Returns a new instance of Randomizer.

Raises:

  • (ArgumentError)


167
168
169
170
# File 'lib/keybox/randomizer.rb', line 167

def initialize(random_source_klass = ::Keybox::RandomSource)
    raise ArgumentError, "Invalid random source class" unless random_source_klass.respond_to?("rand")
    @random_source = random_source_klass
end

Instance Attribute Details

#random_sourceObject (readonly)

Returns the value of attribute random_source.



165
166
167
# File 'lib/keybox/randomizer.rb', line 165

def random_source
  @random_source
end

Instance Method Details

#pick_count_from(array, count = 1) ⇒ Object

Raises:

  • (ArgumentError)


176
177
178
179
180
181
182
183
184
185
# File 'lib/keybox/randomizer.rb', line 176

def pick_count_from(array, count = 1)
    raise ArgumentError, "Unable to pick from object of class #{array.class.name}" unless has_correct_duck_type?(array)
    results = []
    range = array.size
    count.times do
        rand_index = random_source.rand(range)
        results << array.at(rand_index)
    end
    results
end

#pick_one_from(array) ⇒ Object



172
173
174
# File 'lib/keybox/randomizer.rb', line 172

def pick_one_from(array)
    pick_count_from(array).first
end