Module: Random::StringExtensions

Included in:
String
Defined in:
lib/standard/facets/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



360
361
362
# File 'lib/standard/facets/random.rb', line 360

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.

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


399
400
401
402
# File 'lib/standard/facets/random.rb', line 399

def at_rand( separator=// )
  #separator = self.class.patterns( 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.

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


411
412
413
414
415
416
417
418
419
# File 'lib/standard/facets/random.rb', line 411

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

#rand_byteObject

Return a random byte of self.

"Ruby rules".rand_byte  #~> 121


425
426
427
# File 'lib/standard/facets/random.rb', line 425

def rand_byte
  self[Random.number(size)]
end

#rand_byte!Object

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

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


435
436
437
438
439
440
# File 'lib/standard/facets/random.rb', line 435

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

#rand_indexObject

Return a random string index.

"Ruby rules".rand_index  #~> 3


446
447
448
# File 'lib/standard/facets/random.rb', line 446

def rand_index
  Random.number(size)
end

#shuffle(separator = //) ⇒ Object

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

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


455
456
457
# File 'lib/standard/facets/random.rb', line 455

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

#shuffle!(separator = //) ⇒ Object

In place version of shuffle.



461
462
463
# File 'lib/standard/facets/random.rb', line 461

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