Sha256: d98077710cd078cc908e625224d0048d8d2b54b436684905edec3e490d8dcfa0

Contents?: true

Size: 1.24 KB

Versions: 26

Compression:

Stored size: 1.24 KB

Contents

class Array

  # Similar to #at_rand, but will return an array of randomly
  # picked exclusive elements if given a number.
  def pick(n=nil)
    if n
      a = self.dup
      a.pick!(n)
    else
      at( Kernel.rand( size ) )
    end
  end

  # Similar to #at_rand!, but given a number will return
  # an array of exclusive elements.
  def pick!(n=nil)
    if n
      if n > self.size
        r = self.dup
        self.replace([])
        r
      else
        r = []
        n.times { r << delete_at( Kernel.rand( size ) ) }
        r
      end
    else
      delete_at( Kernel.rand( size ) )
    end
  end

end


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

  require 'test/unit'

  class TCArray < Test::Unit::TestCase

    def test_pick
      a = ['a','b','c']
      assert_equal( 3, a.pick(3).length )
      assert_equal( 3, a.length )
      a = ['a','b','c']
      assert_equal( 3, a.pick(4).length )
      assert_equal( 3, a.length )
    end

    def test_pick!
      a = ['a','b','c']
      assert_equal( 3, a.pick!(3).length )
      assert_equal( 0, a.length )
      a = ['a','b','c']
      assert_equal( 3, a.pick!(4).length )
      assert_equal( 0, a.length )
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

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