summaryrefslogtreecommitdiff
path: root/array.c
diff options
context:
space:
mode:
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("<=>");
}