summaryrefslogtreecommitdiff
path: root/array.c
diff options
context:
space:
mode:
authormatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2007-05-01 08:45:28 +0000
committermatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2007-05-01 08:45:28 +0000
commit2b6252e64e47de5973218ec4655de169bdddc884 (patch)
treea3e27b43038aa467cb302ad41535953b248d73fe /array.c
parentf80841275d23122872e528f75f975270cb7b1624 (diff)
* 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
Diffstat (limited to 'array.c')
-rw-r--r--array.c21
1 files changed, 20 insertions, 1 deletions
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("<=>");
}