* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / array.rb
blobb9fa9844e69cf462ccb7d88a10e9e68c44377f3b
1 class Array
2   # call-seq:
3   #    array.shuffle!(random: Random) -> array
4   #
5   # Shuffles the elements of +self+ in place.
6   #    a = [1, 2, 3] #=> [1, 2, 3]
7   #    a.shuffle!    #=> [2, 3, 1]
8   #    a             #=> [2, 3, 1]
9   #
10   # The optional +random+ argument will be used as the random number generator:
11   #    a.shuffle!(random: Random.new(1))  #=> [1, 3, 2]
12   def shuffle!(random: Random)
13     Primitive.rb_ary_shuffle_bang(random)
14   end
16   # call-seq:
17   #    array.shuffle(random: Random) -> new_ary
18   #
19   # Returns a new array with elements of +self+ shuffled.
20   #    a = [1, 2, 3] #=> [1, 2, 3]
21   #    a.shuffle     #=> [2, 3, 1]
22   #    a             #=> [1, 2, 3]
23   #
24   # The optional +random+ argument will be used as the random number generator:
25   #    a.shuffle(random: Random.new(1))  #=> [1, 3, 2]
26   def shuffle(random: Random)
27     Primitive.rb_ary_shuffle(random)
28   end
30   # call-seq:
31   #    array.sample(random: Random) -> object
32   #    array.sample(n, random: Random) -> new_ary
33   #
34   # Returns random elements from +self+.
35   #
36   # When no arguments are given, returns a random element from +self+:
37   #    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
38   #    a.sample # => 3
39   #    a.sample # => 8
40   # If +self+ is empty, returns +nil+.
41   #
42   # When argument +n+ is given, returns a new \Array containing +n+ random
43   # elements from +self+:
44   #    a.sample(3) # => [8, 9, 2]
45   #    a.sample(6) # => [9, 6, 10, 3, 1, 4]
46   # Returns no more than <tt>a.size</tt> elements
47   # (because no new duplicates are introduced):
48   #    a.sample(a.size * 2) # => [6, 4, 1, 8, 5, 9, 10, 2, 3, 7]
49   # But +self+ may contain duplicates:
50   #    a = [1, 1, 1, 2, 2, 3]
51   #    a.sample(a.size * 2) # => [1, 1, 3, 2, 1, 2]
52   # The argument +n+ must be a non-negative numeric value.
53   # The order of the result array is unrelated to the order of +self+.
54   # Returns a new empty \Array if +self+ is empty.
55   #
56   # The optional +random+ argument will be used as the random number generator:
57   #    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
58   #    a.sample(random: Random.new(1))     #=> 6
59   #    a.sample(4, random: Random.new(1))  #=> [6, 10, 9, 2]
60   def sample(n = (ary = false), random: Random)
61     if Primitive.mandatory_only?
62       # Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) }
63       Primitive.ary_sample0
64     else
65       # Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) }
66       Primitive.ary_sample(random, n, ary)
67     end
68   end
69 end