class method self.random_number

Ruby on Rails 2.2.3

Since v2.2.3 Last seen in v3.0.20

Available in: v2.2.3 v2.3.18 v3.0.20

Signature

self.random_number(n=0)

SecureRandom.random_number generates a random number.

If an positive integer is given as n, SecureRandom.random_number returns an integer: 0 <= SecureRandom.random_number(n) < n.

If 0 is given or an argument is not given, SecureRandom.random_number returns an float: 0.0 <= SecureRandom.random_number() < 1.0.

Parameters

n opt = 0
Source
# File activesupport/lib/active_support/secure_random.rb, line 162
      def self.random_number(n=0)
        if 0 < n
          hex = n.to_s(16)
          hex = '0' + hex if (hex.length & 1) == 1
          bin = [hex].pack("H*")
          mask = bin[0]
          mask |= mask >> 1
          mask |= mask >> 2
          mask |= mask >> 4
          begin
            rnd = SecureRandom.random_bytes(bin.length)
            rnd[0] = rnd[0] & mask
          end until rnd < bin
          rnd.unpack("H*")[0].hex
        else
          # assumption: Float::MANT_DIG <= 64
          i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
          Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
        end
      end

Defined in activesupport/lib/active_support/secure_random.rb line 162 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::SecureRandom

Type at least 2 characters to search.

↑↓ navigate · open · esc close