Skip to content
instance method

Random::Formatter#random_bytes

random_bytes(n=nil)

Generate a random binary string.

The argument n specifies the length of the result string.

If n is not specified or is nil, 16 is assumed. It may be larger in future.

The result may contain any byte: “\x00” - “\xff”.

Example
require 'random/formatter'

Random.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
# or
prng = Random.new
prng.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
See also #rand #random_number #hex #urlsafe_base64 also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0