module RandomWord::EachRandomly

Attributes

max_length[RW]
min_length[RW]
random_word_exclude_list[RW]

Public Class Methods

extended(mod) click to toggle source
# File lib/random-word/lib/random_word.rb, line 41
def self.extended(mod)
  mod.set_constraints
end

Public Instance Methods

each_randomly() { |word| ... } click to toggle source
# File lib/random-word/lib/random_word.rb, line 16
def each_randomly(&blk)
  used = Set.new
  skipped = Set.new
  loop do
    idx = next_unused_idx(used)
    used << idx
    word = at(idx)
    if excluded?(word)
      skipped << idx
      next
    end
    yield word
    used.subtract(skipped)
    skipped.clear
  end

rescue OutOfWords
  # we are done.
end
set_constraints(opts = {}) click to toggle source
# File lib/random-word/lib/random_word.rb, line 36
def set_constraints(opts = {})
  @min_length = opts[:not_shorter_than] || 1
  @max_length = opts[:not_longer_than] || Float::INFINITY
end

Private Instance Methods

excluded?(word) click to toggle source
# File lib/random-word/lib/random_word.rb, line 59
def excluded?(word)
  exclude_list = Array(@random_word_exclude_list)
  (
    word.nil? ||
    exclude_list.any? {|r| r === word} ||
    word.length < min_length ||
    (!(max_length.nil?) && word.length > max_length)
  )
end
next_unused_idx(used) click to toggle source
# File lib/random-word/lib/random_word.rb, line 47
def next_unused_idx(used)
  idx = rand(length)
  try = 1
  while used.include?(idx)
    raise OutOfWords if try > 1000
    idx = rand(length)
    try += 1
  end

  idx
end