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.8.0 lib/facets/core/array/pick.rb
facets-1.8.20 lib/facets/core/array/pick.rb
facets-1.8.49 lib/facets/core/array/pick.rb
facets-1.8.51 lib/facets/core/array/pick.rb
facets-1.8.54 lib/facets/core/array/pick.rb
facets-1.8.8 lib/facets/core/array/pick.rb