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

This commit is contained in:
Koichi Sasada 2021-11-13 02:15:09 +09:00
Родитель b1b73936c1
Коммит a24eeee556
2 изменённых файлов: 14 добавлений и 2 удалений

Просмотреть файл

@ -6337,7 +6337,7 @@ rb_ary_shuffle(rb_execution_context_t *ec, VALUE ary, VALUE randgen)
} }
static VALUE 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; VALUE result;
long n, len, i, j, k, idx[10]; 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; return result;
} }
static VALUE
ary_sample0(rb_execution_context_t *ec, VALUE ary)
{
return ary_sample(ec, ary, rb_cRandom, Qfalse, Qfalse);
}
static VALUE static VALUE
rb_ary_cycle_size(VALUE self, VALUE args, VALUE eobj) rb_ary_cycle_size(VALUE self, VALUE args, VALUE eobj)
{ {

Просмотреть файл

@ -58,6 +58,12 @@ class Array
# a.sample(random: Random.new(1)) #=> 6 # a.sample(random: Random.new(1)) #=> 6
# a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2] # a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2]
def sample(n = (ary = false), random: Random) 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
end end