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 legnth of characters (default 8) and an optional valid char Regexp (default /wd/).

String.random    #~> 'dd4qed4r'

CREDIT George Moschovitis – TODO: This is not very efficient. Better way? ++

Raises:

  • (ArgumentError)


353
354
355
356
357
358
359
360
361
# File 'lib/standard/facets/random.rb', line 353

def random(max_length = 8, char_re = /[\w\d]/)
  raise ArgumentError.new('char_re 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