Module: Random::StringExtensions::Self

Defined in:
lib/standard/facets/random.rb

Overview

Class-level methods.

Instance Method Summary collapse

Instance Method Details

#random(max_length = 8, char_re = /[\w\d]/) ⇒ Object

Returns a randomly generated string. One possible use is password initialization. Takes a max length of characters (default 8) and an optional valid char Regexp (default /\w\d/).

String.random    #~> 'dd4qed4r'

CREDIT George Moschovitis

Raises:

  • (ArgumentError)


292
293
294
295
296
297
298
299
300
# File 'lib/standard/facets/random.rb', line 292

def random(max_length = 8, char_re = /[\w\d]/)
  raise ArgumentError.new('second argument must be a regular expression') unless char_re.is_a?(Regexp)
  string = ""
  while string.length < max_length
      ch = Random.number(255).chr
      string << ch if ch =~ char_re
  end
  return string
end

#random_binary(n_bytes) ⇒ Object

Generate a random binary string of n_bytes size.

CREDIT: Guido De Rosa



305
306
307
# File 'lib/standard/facets/random.rb', line 305

def random_binary(n_bytes)
  ( Array.new(n_bytes){ rand(0x100) } ).pack('c*')
end