Module: Backports::Random::Implementation

Included in:
Random, Random
Defined in:
lib/backports/random/implementation.rb

Overview

Implementation corresponding to the actual Random class of Ruby The actual random generator (mersenne twister) is in MT19937. Ruby specific conversions are handled in bits_and_bytes. The high level stuff (argument checking) is done here.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#seedObject (readonly)

Returns the value of attribute seed


13
14
15
# File 'lib/backports/random/implementation.rb', line 13

def seed
  @seed
end

Instance Method Details

#==(other) ⇒ Object


47
48
49
50
51
52
# File 'lib/backports/random/implementation.rb', line 47

def ==(other)
  other.is_a?(::Random) &&
    seed == other.seed &&
    left == other.send(:left) &&
    state == other.send(:state)
end

#bytes(nb) ⇒ Object

Raises:

  • (ArgumentError)

41
42
43
44
45
# File 'lib/backports/random/implementation.rb', line 41

def bytes(nb)
  nb = Backports.coerce_to_int(nb)
  raise ArgumentError, "negative size" if nb < 0
  @mt.random_bytes(nb)
end

#initialize(seed = 0) ⇒ Object


15
16
17
18
# File 'lib/backports/random/implementation.rb', line 15

def initialize(seed = 0)
  super()
  srand(seed)
end

#marshal_dumpObject


54
55
56
# File 'lib/backports/random/implementation.rb', line 54

def marshal_dump
  @mt.marshal_dump << @seed
end

#marshal_load(ary) ⇒ Object


58
59
60
61
62
# File 'lib/backports/random/implementation.rb', line 58

def marshal_load(ary)
  @seed = ary.pop
  @mt = MT19937.allocate
  @mt.marshal_load(ary)
end

#rand(limit = Backports::Undefined) ⇒ Object


27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/backports/random/implementation.rb', line 27

def rand(limit = Backports::Undefined)
  case limit
    when Backports::Undefined
      @mt.random_float
    when Float
      limit * @mt.random_float unless limit <= 0
    when Range
      _rand_range(limit)
    else
      limit = Backports.coerce_to_int(limit)
      @mt.random_integer(limit) unless limit <= 0
  end || raise(ArgumentError, "invalid argument #{limit}")
end

#srand(new_seed = 0) ⇒ Object


20
21
22
23
24
25
# File 'lib/backports/random/implementation.rb', line 20

def srand(new_seed = 0)
  new_seed = Backports.coerce_to_int(new_seed)
  old, @seed = @seed, new_seed.nonzero? || ::Random.new_seed
  @mt = MT19937[ @seed ]
  old
end