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
-
#at_rand(separator = //) ⇒ Object
Return a random separation of the string.
-
#at_rand!(separator = //) ⇒ Object
Return a random separation while removing it from the string.
-
#rand_byte ⇒ Object
Return a random byte of self.
-
#rand_byte! ⇒ Object
Destructive rand_byte.
-
#rand_index ⇒ Object
Return a random string index.
-
#shuffle(separator = //) ⇒ Object
Return the string with separated sections arranged in a random order.
-
#shuffle!(separator = //) ⇒ Object
In place version of shuffle.
Class Method Details
Instance Method Details
#at_rand(separator = //) ⇒ Object
Return a random separation of the string. Default separation is by character.
"Ruby rules".at_rand(' ') #~> ["Ruby"]
315 316 317 |
# File 'lib/standard/facets/random.rb', line 315 def at_rand( separator=// ) self.split(separator,-1).sample 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"
326 327 328 329 330 331 332 333 |
# File 'lib/standard/facets/random.rb', line 326 def at_rand!( 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_byte ⇒ Object
Return a random byte of self.
"Ruby rules".rand_byte #~> 121
339 340 341 |
# File 'lib/standard/facets/random.rb', line 339 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"
349 350 351 352 353 354 |
# File 'lib/standard/facets/random.rb', line 349 def rand_byte! i = Random.number(size) rv = self[i,1] self[i,1] = '' rv end |
#rand_index ⇒ Object
Return a random string index.
"Ruby rules".rand_index #~> 3
360 361 362 |
# File 'lib/standard/facets/random.rb', line 360 def rand_index Random.number(size) end |
#shuffle(separator = //) ⇒ Object
Return the string with separated sections arranged in a random order. The default separation is by character.
"Ruby rules".shuffle #~> "e lybRsuur"
369 370 371 |
# File 'lib/standard/facets/random.rb', line 369 def shuffle(separator=//) split(separator).shuffle.join('') end |
#shuffle!(separator = //) ⇒ Object
In place version of shuffle.
375 376 377 |
# File 'lib/standard/facets/random.rb', line 375 def shuffle!(separator=//) self.replace( shuffle(separator) ) end |