From 2b6252e64e47de5973218ec4655de169bdddc884 Mon Sep 17 00:00:00 2001 From: matz Date: Tue, 1 May 2007 08:45:28 +0000 Subject: [PATCH] * 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 --- ChangeLog | 5 +++++ array.c | 21 ++++++++++++++++++++- version.h | 2 ++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index a16bc8eca5..242e3060f3 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Tue May 1 17:46:05 2007 Yukihiro Matsumoto + + * 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 * proc.c (proc_arity): fix an arity bug ([ruby-core:11060]). diff --git a/array.c b/array.c index ac68bd4e0c..7639e22a1a 100644 --- a/array.c +++ b/array.c @@ -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("<=>"); } diff --git a/version.h b/version.h index d383b3303f..2dc91ff3ed 100644 --- a/version.h +++ b/version.h @@ -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