Sha256: 5c3759a37b306744215ecead1ae111bec3993c529ba442b7823c9bc5a2ee37e4

Contents?: true

Size: 1.34 KB

Versions: 22

Compression:

Stored size: 1.34 KB

Contents

require 'facet/array/at_rand'
require 'facet/string/self/patterns'
require 'facet/string/shatter'

class String

  # Return a random separation of the string.
  # Default separation is by charaacter.
  #
  #   "Ruby rules".at_rand(' ')  #=> ["Ruby"]
  #
  def at_rand( separator=// )
    separator = self.class.patterns( separator )
    self.split(separator,-1).at_rand
  end

  # Return a random separation while removing it
  # from the string. Default separation is by character.
  #
  #   s = "Ruby rules"
  #   s = at_rand!(' ')  #=> "Ruby"
  #   s                  #=> "rules"
  #
  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 = rand( w.size )
    r = w.delete_at( i )
    self.replace( w.join('') )
    return r
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCString < Test::Unit::TestCase

    def test_at_rand
      a = '12345'
      20.times{ assert_nothing_raised{ a.at_rand } }
      20.times{ assert( a.include?( a.at_rand ) ) }
    end

    def test_at_rand!
      x = 'ab'
      r = x.at_rand!
      assert( r == 'a' || r == 'b' )
      assert( x == 'a' || x == 'b' )
    end

  end

=end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/string/at_rand.rb
facets-1.0.3 packages/core/lib/facet/string/at_rand.rb
facets-1.3.0 lib/facets/core/string/at_rand.rb
facets-1.1.0 lib/facet/string/at_rand.rb
facets-1.2.0 lib/facets/core/string/at_rand.rb
facets-1.2.1 lib/facets/core/string/at_rand.rb
facets-1.3.3 lib/facets/core/string/at_rand.rb
facets-1.3.2 lib/facets/core/string/at_rand.rb
facets-1.3.1 lib/facets/core/string/at_rand.rb
facets-1.4.0 lib/facets/core/string/at_rand.rb
facets-1.4.2 lib/facets/core/string/at_rand.rb
facets-1.4.1 lib/facets/core/string/at_rand.rb
facets-1.4.3 lib/facets/core/string/at_rand.rb
facets-1.4.5 lib/facets/core/string/at_rand.rb
facets-1.4.4 lib/facets/core/string/at_rand.rb
facets-1.7.30 lib/facets/core/string/at_rand.rb
facets-1.7.0 lib/facets/core/string/at_rand.rb
facets-1.7.38 lib/facets/core/string/at_rand.rb
facets-1.7.46 lib/facets/core/string/at_rand.rb
facets-1.8.20 lib/facets/core/string/at_rand.rb