mirror of
https://github.com/ruby/ruby.git
synced 2026-10-28 16:36:20 +08:00
Dispatch Array#sample in array.rb
This commit is contained in:
2 files changed
+19
-20
Notes:
git
2026-10-16 10:05:40 +00:00
No files matched your search
@@ -7032,22 +7032,27 @@ static const rb_data_type_t ary_sample_memo_type = {
|
||||
};
|
||||
|
||||
static VALUE
|
||||
ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array)
|
||||
ary_sample1(rb_execution_context_t *ec, VALUE ary, const VALUE randgen)
|
||||
{
|
||||
rb_len_t len = RARRAY_LEN(ary);
|
||||
rb_len_t i = (len < 2) ? 0 : RAND_UPTO(len);
|
||||
return rb_ary_elt(ary, i);
|
||||
}
|
||||
|
||||
static VALUE
|
||||
ary_sample0(rb_execution_context_t *ec, VALUE ary)
|
||||
{
|
||||
return ary_sample1(ec, ary, rb_cRandom);
|
||||
}
|
||||
|
||||
static VALUE
|
||||
ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv)
|
||||
{
|
||||
VALUE result;
|
||||
rb_len_t n, len, i, j, k, idx[10];
|
||||
rb_len_t rnds[numberof(idx)];
|
||||
rb_len_t memo_threshold;
|
||||
|
||||
if (!to_array) {
|
||||
len = RARRAY_LEN(ary);
|
||||
if (len < 2)
|
||||
i = 0;
|
||||
else
|
||||
i = RAND_UPTO(len);
|
||||
|
||||
return rb_ary_elt(ary, i);
|
||||
}
|
||||
n = NUM2LEN(nv);
|
||||
if (n < 0) rb_raise(rb_eArgError, "negative sample number");
|
||||
len = RARRAY_LEN(ary);
|
||||
@@ -7167,12 +7172,6 @@ ary_sized_alloc(rb_execution_context_t *ec, VALUE self)
|
||||
return rb_ary_new2(RARRAY_LEN(self));
|
||||
}
|
||||
|
||||
static VALUE
|
||||
ary_sample0(rb_execution_context_t *ec, VALUE ary)
|
||||
{
|
||||
return ary_sample(ec, ary, rb_cRandom, Qfalse, Qfalse);
|
||||
}
|
||||
|
||||
static VALUE
|
||||
rb_ary_cycle_size(VALUE self, VALUE args, VALUE eobj)
|
||||
{
|
||||
|
||||
@@ -92,13 +92,13 @@ class Array
|
||||
# a.sample(4, random: Random.new(1)) # => [6, 10, 9, 2]
|
||||
#
|
||||
# Related: see {Methods for Fetching}[rdoc-ref:Array@Methods+for+Fetching].
|
||||
def sample(n = (ary = false), random: Random)
|
||||
def sample(n = (single = true), random: Random)
|
||||
if Primitive.mandatory_only?
|
||||
# Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) }
|
||||
Primitive.ary_sample0
|
||||
elsif single
|
||||
Primitive.ary_sample1(random)
|
||||
else
|
||||
# Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) }
|
||||
Primitive.ary_sample(random, n, ary)
|
||||
Primitive.ary_sample(random, n)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
Reference in new issue
Block a user