Module: Random::StringExtensions::Self

Defined in:
lib/garcon/core_ext/random.rb

Overview

Class-level methods.

Instance Method Summary collapse

Instance Method Details

#ran(len = 32, character_set = ["A".."Z", "a".."z", "0".."9"]) ⇒ Object

Create a random String of given length, using given character set

Examples

String.random
=> "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"

String.ran(10)
=> "t8BIna341S"

String.ran(10, ['a'..'z'])
=> "nstpvixfri"

String.ran(10, ['0'..'9'] )
=> "0982541042"

String.ran(10, ['0'..'9','A'..'F'] )
=> "3EBF48AD3D"


409
410
411
412
# File 'lib/garcon/core_ext/random.rb', line 409

def ran(len = 32, character_set = ["A".."Z", "a".."z", "0".."9"])
  chars = character_set.map(&:to_a).flatten
  Array.new(len){ chars.sample }.join
end

#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/).

Examples:

String.random    # => 'dd4qed4r'


371
372
373
374
375
376
377
378
379
380
381
# File 'lib/garcon/core_ext/random.rb', line 371

def random(max_length = 8, char_re = /[\w\d]/)
  unless char_re.is_a?(Regexp)
    raise ArgumentError, 'second argument must be a regular expression'
  end
  string = ''
  while string.length < max_length
      ch = SecureRandom.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.



385
386
387
388
# File 'lib/garcon/core_ext/random.rb', line 385

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