diff options
-rw-r--r-- | ChangeLog | 5 | ||||
-rw-r--r-- | array.c | 21 | ||||
-rw-r--r-- | version.h | 2 |
3 files changed, 27 insertions, 1 deletions
@@ -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]). @@ -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("<=>"); } @@ -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 |