Module: Random::StringExtensions

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

Overview

Random extensions for String class.

Defined Under Namespace

Modules: Self

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



358
359
360
# File 'lib/garcon/core_ext/random.rb', line 358

def self.included(base)
  base.extend(Self)
end

Instance Method Details

#at_rand(separator = //) ⇒ Object

Return a random separation of the string. Default separation is by charaacter.

Examples:

"Ruby rules".at_rand(' ')  # => ["Ruby"]


421
422
423
# File 'lib/garcon/core_ext/random.rb', line 421

def at_rand(separator = //)
  self.split(separator, -1).at_rand
end

#at_rand!(separator = //) ⇒ Object

Return a random separation while removing it from the string. Default separation is by character.

Examples:

s = "Ruby rules"
s.at_rand!(' ')    # => "Ruby"
s                  # => "rules"


433
434
435
436
437
438
439
440
# File 'lib/garcon/core_ext/random.rb', line 433

def at_rand!(separator = //)
  a = self.shatter(separator)
  w = []; a.each_with_index { |s, i| i % 2 == 0 ? w << s : w.last << s }
  i = SecureRandom.random_number(w.size)
  r = w.delete_at(i)
  self.replace(w.join(''))
  return r
end

#rand_byteObject

Return a random byte of self.

Examples:

"Ruby rules".rand_byte  # => 121


447
448
449
# File 'lib/garcon/core_ext/random.rb', line 447

def rand_byte
  self[SecureRandom.random_number(size)]
end

#rand_byte!Object

Destructive rand_byte. Delete a random byte of self and return it.

Examples:

s = "Ruby rules"
s.rand_byte!      # => 121
s                 # => "Rub rules"


458
459
460
461
462
463
# File 'lib/garcon/core_ext/random.rb', line 458

def rand_byte!
  i = SecureRandom.random_number(size)
  rv = self[i,1]
  self[i,1] = ''
  rv
end

#rand_indexObject

Return a random string index.

Examples:

"Ruby rules".rand_index  # => 3


470
471
472
# File 'lib/garcon/core_ext/random.rb', line 470

def rand_index
  SecureRandom.random_number(size)
end

#shuffle(separator = //) ⇒ Object

Return the string with seperated sections arranged in a random order. The default seperation is by character.

Examples:

"Ruby rules".shuffle  # => "e lybRsuur"


480
481
482
# File 'lib/garcon/core_ext/random.rb', line 480

def shuffle(separator = //)
  split(separator).shuffle.join('')
end

#shuffle!(separator = //) ⇒ Object

In place version of shuffle.



486
487
488
# File 'lib/garcon/core_ext/random.rb', line 486

def shuffle!(separator = //)
  self.replace(shuffle(separator))
end