Class: Fakir::Array

Inherits:
Array
  • Object
show all
Defined in:
lib/fakir/array.rb

Overview

Extends the ::Array class to return random elements, where an element is returned only once. rand_reset resets the rand method to return elements from the original array, i.e., to possibly repeat elements from before rand_reset was invoked.

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Array

Returns a new instance of Array.



9
10
11
12
13
# File 'lib/fakir/array.rb', line 9

def initialize(*args)
  @used = ::Array.new
  rand_reset
  super
end

Instance Method Details

#randObject



20
21
22
23
24
25
26
27
28
# File 'lib/fakir/array.rb', line 20

def rand
  if size == 0
    raise "error: cannot get random element from an empty array"
  end
  idx = Kernel::rand size
  val = delete_at idx
  @used << val
  val
end

#rand_resetObject



15
16
17
18
# File 'lib/fakir/array.rb', line 15

def rand_reset
  concat @used
  @used = ::Array.new
end