Use `Primitive.mandatory_only?` for `Array#sample`

This commit is contained in:
Koichi Sasada 2021-11-13 02:15:09 +09:00
parent b1b73936c1
commit a24eeee556
Notes: git 2021-11-15 15:59:20 +09:00
2 changed files with 14 additions and 2 deletions

View File

@ -6337,7 +6337,7 @@ rb_ary_shuffle(rb_execution_context_t *ec, VALUE ary, VALUE randgen)
}
static VALUE
rb_ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array)
ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array)
{
VALUE result;
long n, len, i, j, k, idx[10];
@ -6466,6 +6466,12 @@ rb_ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VA
return result;
}
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)
{

View File

@ -58,6 +58,12 @@ class Array
# a.sample(random: Random.new(1)) #=> 6
# a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2]
def sample(n = (ary = false), random: Random)
Primitive.rb_ary_sample(random, n, ary)
if Primitive.mandatory_only?
# Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) }
Primitive.ary_sample0
else
# Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) }
Primitive.ary_sample(random, n, ary)
end
end
end