1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

* array.c (rb_ary_choice): a new method to choose an element

randomly from an array.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@12233 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
matz 2007-05-01 08:45:28 +00:00
parent f80841275d
commit 2b6252e64e
3 changed files with 27 additions and 1 deletions

View file

@ -1,3 +1,8 @@
Tue May 1 17:46:05 2007 Yukihiro Matsumoto <matz@ruby-lang.org>
* array.c (rb_ary_choice): a new method to choose an element
randomly from an array.
Tue May 1 13:59:18 2007 Koichi Sasada <ko1@atdot.net>
* proc.c (proc_arity): fix an arity bug ([ruby-core:11060]).

21
array.c
View file

@ -2899,7 +2899,7 @@ rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
/*
* call-seq:
* array.shuffle! -> array or
* array.shuffle! -> array or nil
*
* Shuffles elements in _self_ in place.
*/
@ -2941,6 +2941,24 @@ rb_ary_shuffle(VALUE ary)
}
/*
* call-seq:
* array.choice -> an_array
*
* Choose a random element from an array.
*/
static VALUE
rb_ary_choice(VALUE ary)
{
long i = RARRAY_LEN(ary);
long j = genrand_real()*i;
return RARRAY_PTR(ary)[j];
}
/* Arrays are ordered, integer-indexed collections of any object.
* Array indexing starts at 0, as in C or Java. A negative index is
* assumed to be relative to the end of the array---that is, an index of -1
@ -3037,6 +3055,7 @@ Init_Array(void)
rb_define_method(rb_cArray, "nitems", rb_ary_nitems, 0);
rb_define_method(rb_cArray, "shuffle!", rb_ary_shuffle_bang, 0);
rb_define_method(rb_cArray, "shuffle", rb_ary_shuffle, 0);
rb_define_method(rb_cArray, "choice", rb_ary_choice, 0);
id_cmp = rb_intern("<=>");
}

View file

@ -11,7 +11,9 @@
#define RUBY_RELEASE_MONTH 5
#define RUBY_RELEASE_DAY 1
#ifdef RUBY_EXTERN
RUBY_EXTERN const char ruby_version[];
RUBY_EXTERN const char ruby_release_date[];
RUBY_EXTERN const char ruby_platform[];
RUBY_EXTERN const int ruby_patchlevel;
#endif