1 /**********************************************************************
6 created at: Fri Oct 1 15:15:19 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
13 #include "ruby/node.h"
14 #include "ruby/util.h"
17 static ID id_each
, id_eqq
, id_cmp
, id_next
, id_size
;
20 enum_values_pack(int argc
, VALUE
*argv
)
22 if (argc
== 0) return Qnil
;
23 if (argc
== 1) return argv
[0];
24 return rb_ary_new4(argc
, argv
);
27 #define ENUM_WANT_SVALUE() do { \
28 i = enum_values_pack(argc, argv); \
31 #define enum_yield rb_yield_values2
34 grep_i(VALUE i
, VALUE
*arg
, int argc
, VALUE
*argv
)
38 if (RTEST(rb_funcall(arg
[0], id_eqq
, 1, i
))) {
39 rb_ary_push(arg
[1], i
);
45 grep_iter_i(VALUE i
, VALUE
*arg
, int argc
, VALUE
*argv
)
49 if (RTEST(rb_funcall(arg
[0], id_eqq
, 1, i
))) {
50 rb_ary_push(arg
[1], rb_yield(i
));
57 * enum.grep(pattern) => array
58 * enum.grep(pattern) {| obj | block } => array
60 * Returns an array of every element in <i>enum</i> for which
61 * <code>Pattern === element</code>. If the optional <em>block</em> is
62 * supplied, each matching element is passed to it, and the block's
63 * result is stored in the output array.
65 * (1..100).grep 38..44 #=> [38, 39, 40, 41, 42, 43, 44]
67 * c.grep(/SEEK/) #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END]
68 * res = c.grep(/SEEK/) {|v| IO.const_get(v) }
74 enum_grep(VALUE obj
, VALUE pat
)
76 VALUE ary
= rb_ary_new();
82 rb_block_call(obj
, id_each
, 0, 0, rb_block_given_p() ? grep_iter_i
: grep_i
, (VALUE
)arg
);
88 count_i(VALUE i
, VALUE memop
, int argc
, VALUE
*argv
)
90 VALUE
*memo
= (VALUE
*)memop
;
94 if (rb_equal(i
, memo
[1])) {
101 count_iter_i(VALUE i
, VALUE memop
, int argc
, VALUE
*argv
)
103 VALUE
*memo
= (VALUE
*)memop
;
105 if (RTEST(enum_yield(argc
, argv
))) {
112 count_all_i(VALUE i
, VALUE memop
, int argc
, VALUE
*argv
)
114 VALUE
*memo
= (VALUE
*)memop
;
123 * enum.count(item) => int
124 * enum.count {| obj | block } => int
126 * Returns the number of items in <i>enum</i>, where #size is called
127 * if it responds to it, otherwise the items are counted through
128 * enumeration. If an argument is given, counts the number of items
129 * in <i>enum</i>, for which equals to <i>item</i>. If a block is
130 * given, counts the number of elements yielding a true value.
134 * ary.count(2) # => 2
135 * ary.count{|x|x%2==0} # => 3
140 enum_count(int argc
, VALUE
*argv
, VALUE obj
)
142 VALUE memo
[2]; /* [count, condition value] */
143 rb_block_call_func
*func
;
146 if (rb_block_given_p()) {
150 if (rb_respond_to(obj
, id_size
)) {
151 return rb_funcall(obj
, id_size
, 0, 0);
157 rb_scan_args(argc
, argv
, "1", &memo
[1]);
158 if (rb_block_given_p()) {
159 rb_warn("given block not used");
165 rb_block_call(obj
, id_each
, 0, 0, func
, (VALUE
)&memo
);
166 return INT2NUM(memo
[0]);
170 find_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
174 if (RTEST(rb_yield(i
))) {
183 * enum.detect(ifnone = nil) {| obj | block } => obj or nil
184 * enum.find(ifnone = nil) {| obj | block } => obj or nil
186 * Passes each entry in <i>enum</i> to <em>block</em>. Returns the
187 * first for which <em>block</em> is not <code>false</code>. If no
188 * object matches, calls <i>ifnone</i> and returns its result when it
189 * is specified, or returns <code>nil</code>
191 * (1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
192 * (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35
197 enum_find(int argc
, VALUE
*argv
, VALUE obj
)
202 rb_scan_args(argc
, argv
, "01", &if_none
);
203 RETURN_ENUMERATOR(obj
, argc
, argv
);
204 rb_block_call(obj
, id_each
, 0, 0, find_i
, (VALUE
)&memo
);
205 if (memo
!= Qundef
) {
208 if (!NIL_P(if_none
)) {
209 return rb_funcall(if_none
, rb_intern("call"), 0, 0);
215 find_index_i(VALUE i
, VALUE memop
, int argc
, VALUE
*argv
)
217 VALUE
*memo
= (VALUE
*)memop
;
221 if (rb_equal(i
, memo
[2])) {
222 memo
[0] = UINT2NUM(memo
[1]);
230 find_index_iter_i(VALUE i
, VALUE memop
, int argc
, VALUE
*argv
)
232 VALUE
*memo
= (VALUE
*)memop
;
234 if (RTEST(enum_yield(argc
, argv
))) {
235 memo
[0] = UINT2NUM(memo
[1]);
244 * enum.find_index(value) => int or nil
245 * enum.find_index {| obj | block } => int or nil
247 * Compares each entry in <i>enum</i> with <em>value</em> or passes
248 * to <em>block</em>. Returns the index for the first for which the
249 * evaluated value is non-false. If no object matches, returns
252 * (1..10).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
253 * (1..100).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> 34
254 * (1..100).find_index(50) #=> 49
259 enum_find_index(int argc
, VALUE
*argv
, VALUE obj
)
261 VALUE memo
[3]; /* [return value, current index, condition value] */
262 rb_block_call_func
*func
;
265 RETURN_ENUMERATOR(obj
, 0, 0);
266 func
= find_index_iter_i
;
269 rb_scan_args(argc
, argv
, "1", &memo
[2]);
270 if (rb_block_given_p()) {
271 rb_warn("given block not used");
278 rb_block_call(obj
, id_each
, 0, 0, func
, (VALUE
)memo
);
283 find_all_i(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
287 if (RTEST(rb_yield(i
))) {
295 * enum.find_all {| obj | block } => array
296 * enum.select {| obj | block } => array
298 * Returns an array containing all elements of <i>enum</i> for which
299 * <em>block</em> is not <code>false</code> (see also
300 * <code>Enumerable#reject</code>).
302 * (1..10).find_all {|i| i % 3 == 0 } #=> [3, 6, 9]
307 enum_find_all(VALUE obj
)
311 RETURN_ENUMERATOR(obj
, 0, 0);
314 rb_block_call(obj
, id_each
, 0, 0, find_all_i
, ary
);
320 reject_i(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
324 if (!RTEST(rb_yield(i
))) {
332 * enum.reject {| obj | block } => array
334 * Returns an array for all elements of <i>enum</i> for which
335 * <em>block</em> is false (see also <code>Enumerable#find_all</code>).
337 * (1..10).reject {|i| i % 3 == 0 } #=> [1, 2, 4, 5, 7, 8, 10]
342 enum_reject(VALUE obj
)
346 RETURN_ENUMERATOR(obj
, 0, 0);
349 rb_block_call(obj
, id_each
, 0, 0, reject_i
, ary
);
355 collect_i(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
357 rb_ary_push(ary
, enum_yield(argc
, argv
));
363 collect_all(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
365 rb_ary_push(ary
, enum_values_pack(argc
, argv
));
372 * enum.collect {| obj | block } => array
373 * enum.map {| obj | block } => array
375 * Returns a new array with the results of running <em>block</em> once
376 * for every element in <i>enum</i>.
378 * (1..4).collect {|i| i*i } #=> [1, 4, 9, 16]
379 * (1..4).collect { "cat" } #=> ["cat", "cat", "cat", "cat"]
384 enum_collect(VALUE obj
)
388 RETURN_ENUMERATOR(obj
, 0, 0);
391 rb_block_call(obj
, id_each
, 0, 0, collect_i
, ary
);
399 * enum.entries => array
401 * Returns an array containing the items in <i>enum</i>.
403 * (1..7).to_a #=> [1, 2, 3, 4, 5, 6, 7]
404 * { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a #=> [["a", 1], ["b", 2], ["c", 3]]
407 enum_to_a(int argc
, VALUE
*argv
, VALUE obj
)
409 VALUE ary
= rb_ary_new();
411 rb_block_call(obj
, id_each
, argc
, argv
, collect_all
, ary
);
417 inject_i(VALUE i
, VALUE p
, int argc
, VALUE
*argv
)
419 VALUE
*memo
= (VALUE
*)p
;
423 if (memo
[0] == Qundef
) {
427 memo
[0] = rb_yield_values(2, memo
[0], i
);
433 inject_op_i(VALUE i
, VALUE p
, int argc
, VALUE
*argv
)
435 VALUE
*memo
= (VALUE
*)p
;
439 if (memo
[0] == Qundef
) {
443 memo
[0] = rb_funcall(memo
[0], (ID
)memo
[1], 1, i
);
450 * enum.inject(initial, sym) => obj
451 * enum.inject(sym) => obj
452 * enum.inject(initial) {| memo, obj | block } => obj
453 * enum.inject {| memo, obj | block } => obj
455 * enum.reduce(initial, sym) => obj
456 * enum.reduce(sym) => obj
457 * enum.reduce(initial) {| memo, obj | block } => obj
458 * enum.reduce {| memo, obj | block } => obj
460 * Combines all elements of <i>enum</i> by applying a binary
461 * operation, specified by a block or a symbol that names a
462 * method or operator.
464 * If you specify a block, then for each element in <i>enum<i>
465 * the block is passed an accumulator value (<i>memo</i>) and the element.
466 * If you specify a symbol instead, then each element in the collection
467 * will be passed to the named method of <i>memo</i>.
468 * In either case, the result becomes the new value for <i>memo</i>.
469 * At the end of the iteration, the final value of <i>memo</i> is the
470 * return value fo the method.
472 * If you do not explicitly specify an <i>initial</i> value for <i>memo</i>,
473 * then uses the first element of collection is used as the initial value
479 * (5..10).reduce(:+) #=> 45
480 * # Same using a block and inject
481 * (5..10).inject {|sum, n| sum + n } #=> 45
482 * # Multiply some numbers
483 * (5..10).reduce(1, :*) #=> 151200
484 * # Same using a block
485 * (5..10).inject(1) {|product, n| product * n } #=> 151200
486 * # find the longest word
487 * longest = %w{ cat sheep bear }.inject do |memo,word|
488 * memo.length > word.length ? memo : word
490 * longest #=> "sheep"
494 enum_inject(int argc
, VALUE
*argv
, VALUE obj
)
497 VALUE (*iter
)(VALUE
, VALUE
, int, VALUE
*) = inject_i
;
499 switch (rb_scan_args(argc
, argv
, "02", &memo
[0], &memo
[1])) {
504 if (rb_block_given_p()) {
507 memo
[1] = (VALUE
)rb_to_id(memo
[0]);
512 if (rb_block_given_p()) {
513 rb_warning("given block not used");
515 memo
[1] = (VALUE
)rb_to_id(memo
[1]);
519 rb_block_call(obj
, id_each
, 0, 0, iter
, (VALUE
)memo
);
520 if (memo
[0] == Qundef
) return Qnil
;
525 partition_i(VALUE i
, VALUE
*ary
, int argc
, VALUE
*argv
)
529 if (RTEST(rb_yield(i
))) {
530 rb_ary_push(ary
[0], i
);
533 rb_ary_push(ary
[1], i
);
540 * enum.partition {| obj | block } => [ true_array, false_array ]
542 * Returns two arrays, the first containing the elements of
543 * <i>enum</i> for which the block evaluates to true, the second
544 * containing the rest.
546 * (1..6).partition {|i| (i&1).zero?} #=> [[2, 4, 6], [1, 3, 5]]
551 enum_partition(VALUE obj
)
555 RETURN_ENUMERATOR(obj
, 0, 0);
557 ary
[0] = rb_ary_new();
558 ary
[1] = rb_ary_new();
559 rb_block_call(obj
, id_each
, 0, 0, partition_i
, (VALUE
)ary
);
561 return rb_assoc_new(ary
[0], ary
[1]);
565 group_by_i(VALUE i
, VALUE hash
, int argc
, VALUE
*argv
)
573 values
= rb_hash_aref(hash
, group
);
575 values
= rb_ary_new3(1, i
);
576 rb_hash_aset(hash
, group
, values
);
579 rb_ary_push(values
, i
);
586 * enum.group_by {| obj | block } => a_hash
588 * Returns a hash, which keys are evaluated result from the
589 * block, and values are arrays of elements in <i>enum</i>
590 * corresponding to the key.
592 * (1..6).group_by {|i| i%3} #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
597 enum_group_by(VALUE obj
)
601 RETURN_ENUMERATOR(obj
, 0, 0);
603 hash
= rb_hash_new();
604 rb_block_call(obj
, id_each
, 0, 0, group_by_i
, hash
);
610 first_i(VALUE i
, VALUE
*ary
, int argc
, VALUE
*argv
)
619 long n
= NUM2LONG(ary
[0]);
624 rb_ary_push(ary
[1], i
);
633 * enum.first -> obj or nil
634 * enum.first(n) -> an_array
636 * Returns the first element, or the first +n+ elements, of the enumerable.
637 * If the enumerable is empty, the first form returns <code>nil</code>, and the
638 * second form returns an empty array.
643 enum_first(int argc
, VALUE
*argv
, VALUE obj
)
648 ary
[0] = ary
[1] = Qnil
;
651 rb_scan_args(argc
, argv
, "01", &n
);
653 ary
[1] = rb_ary_new2(NUM2LONG(n
));
655 rb_block_call(obj
, id_each
, 0, 0, first_i
, (VALUE
)ary
);
664 * enum.sort {| a, b | block } => array
666 * Returns an array containing the items in <i>enum</i> sorted,
667 * either according to their own <code><=></code> method, or by using
668 * the results of the supplied block. The block should return -1, 0, or
669 * +1 depending on the comparison between <i>a</i> and <i>b</i>. As of
670 * Ruby 1.8, the method <code>Enumerable#sort_by</code> implements a
671 * built-in Schwartzian Transform, useful when key computation or
672 * comparison is expensive..
674 * %w(rhea kea flea).sort #=> ["flea", "kea", "rhea"]
675 * (1..10).sort {|a,b| b <=> a} #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
681 return rb_ary_sort(enum_to_a(0, 0, obj
));
685 sort_by_i(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
691 if (RBASIC(ary
)->klass
) {
692 rb_raise(rb_eRuntimeError
, "sort_by reentered");
694 /* use NODE_DOT2 as memo(v, v, -) */
695 memo
= rb_node_newnode(NODE_DOT2
, rb_yield(i
), i
, 0);
696 rb_ary_push(ary
, (VALUE
)memo
);
701 sort_by_cmp(const void *ap
, const void *bp
, void *data
)
703 VALUE a
= (*(NODE
*const *)ap
)->u1
.value
;
704 VALUE b
= (*(NODE
*const *)bp
)->u1
.value
;
705 VALUE ary
= (VALUE
)data
;
707 if (RBASIC(ary
)->klass
) {
708 rb_raise(rb_eRuntimeError
, "sort_by reentered");
710 return rb_cmpint(rb_funcall(a
, id_cmp
, 1, b
), a
, b
);
715 * enum.sort_by {| obj | block } => array
717 * Sorts <i>enum</i> using a set of keys generated by mapping the
718 * values in <i>enum</i> through the given block.
720 * %w{ apple pear fig }.sort_by {|word| word.length}
721 * #=> ["fig", "pear", "apple"]
723 * The current implementation of <code>sort_by</code> generates an
724 * array of tuples containing the original collection element and the
725 * mapped value. This makes <code>sort_by</code> fairly expensive when
726 * the keysets are simple
728 * require 'benchmark'
731 * a = (1..100000).map {rand(100000)}
734 * b.report("Sort") { a.sort }
735 * b.report("Sort by") { a.sort_by {|a| a} }
740 * user system total real
741 * Sort 0.180000 0.000000 0.180000 ( 0.175469)
742 * Sort by 1.980000 0.040000 2.020000 ( 2.013586)
744 * However, consider the case where comparing the keys is a non-trivial
745 * operation. The following code sorts some files on modification time
746 * using the basic <code>sort</code> method.
749 * sorted = files.sort {|a,b| File.new(a).mtime <=> File.new(b).mtime}
750 * sorted #=> ["mon", "tues", "wed", "thurs"]
752 * This sort is inefficient: it generates two new <code>File</code>
753 * objects during every comparison. A slightly better technique is to
754 * use the <code>Kernel#test</code> method to generate the modification
758 * sorted = files.sort { |a,b|
759 * test(?M, a) <=> test(?M, b)
761 * sorted #=> ["mon", "tues", "wed", "thurs"]
763 * This still generates many unnecessary <code>Time</code> objects. A
764 * more efficient technique is to cache the sort keys (modification
765 * times in this case) before the sort. Perl users often call this
766 * approach a Schwartzian Transform, after Randal Schwartz. We
767 * construct a temporary array, where each element is an array
768 * containing our sort key along with the filename. We sort this array,
769 * and then extract the filename from the result.
771 * sorted = Dir["*"].collect { |f|
773 * }.sort.collect { |f| f[1] }
774 * sorted #=> ["mon", "tues", "wed", "thurs"]
776 * This is exactly what <code>sort_by</code> does internally.
778 * sorted = Dir["*"].sort_by {|f| test(?M, f)}
779 * sorted #=> ["mon", "tues", "wed", "thurs"]
783 enum_sort_by(VALUE obj
)
788 RETURN_ENUMERATOR(obj
, 0, 0);
790 if (TYPE(obj
) == T_ARRAY
) {
791 ary
= rb_ary_new2(RARRAY_LEN(obj
));
796 RBASIC(ary
)->klass
= 0;
797 rb_block_call(obj
, id_each
, 0, 0, sort_by_i
, ary
);
798 if (RARRAY_LEN(ary
) > 1) {
799 ruby_qsort(RARRAY_PTR(ary
), RARRAY_LEN(ary
), sizeof(VALUE
),
800 sort_by_cmp
, (void *)ary
);
802 if (RBASIC(ary
)->klass
) {
803 rb_raise(rb_eRuntimeError
, "sort_by reentered");
805 for (i
=0; i
<RARRAY_LEN(ary
); i
++) {
806 RARRAY_PTR(ary
)[i
] = RNODE(RARRAY_PTR(ary
)[i
])->u2
.value
;
808 RBASIC(ary
)->klass
= rb_cArray
;
812 #define DEFINE_ENUMFUNCS(name) \
814 name##_i(VALUE i, VALUE *memo, int argc, VALUE *argv) \
816 return enum_##name##_func(enum_values_pack(argc, argv), memo); \
820 name##_iter_i(VALUE i, VALUE *memo, int argc, VALUE *argv) \
822 return enum_##name##_func(enum_yield(argc, argv), memo); \
826 enum_all_func(VALUE result
, VALUE
*memo
)
828 if (!RTEST(result
)) {
835 DEFINE_ENUMFUNCS(all
)
839 * enum.all? [{|obj| block } ] => true or false
841 * Passes each element of the collection to the given block. The method
842 * returns <code>true</code> if the block never returns
843 * <code>false</code> or <code>nil</code>. If the block is not given,
844 * Ruby adds an implicit block of <code>{|obj| obj}</code> (that is
845 * <code>all?</code> will return <code>true</code> only if none of the
846 * collection members are <code>false</code> or <code>nil</code>.)
848 * %w{ant bear cat}.all? {|word| word.length >= 3} #=> true
849 * %w{ant bear cat}.all? {|word| word.length >= 4} #=> false
850 * [ nil, true, 99 ].all? #=> false
857 VALUE result
= Qtrue
;
859 rb_block_call(obj
, id_each
, 0, 0, rb_block_given_p() ? all_iter_i
: all_i
, (VALUE
)&result
);
864 enum_any_func(VALUE result
, VALUE
*memo
)
873 DEFINE_ENUMFUNCS(any
)
877 * enum.any? [{|obj| block } ] => true or false
879 * Passes each element of the collection to the given block. The method
880 * returns <code>true</code> if the block ever returns a value other
881 * than <code>false</code> or <code>nil</code>. If the block is not
882 * given, Ruby adds an implicit block of <code>{|obj| obj}</code> (that
883 * is <code>any?</code> will return <code>true</code> if at least one
884 * of the collection members is not <code>false</code> or
887 * %w{ant bear cat}.any? {|word| word.length >= 3} #=> true
888 * %w{ant bear cat}.any? {|word| word.length >= 4} #=> true
889 * [ nil, true, 99 ].any? #=> true
896 VALUE result
= Qfalse
;
898 rb_block_call(obj
, id_each
, 0, 0, rb_block_given_p() ? any_iter_i
: any_i
, (VALUE
)&result
);
903 enum_one_func(VALUE result
, VALUE
*memo
)
906 if (*memo
== Qundef
) {
909 else if (*memo
== Qtrue
) {
917 DEFINE_ENUMFUNCS(one
)
921 * enum.one? [{|obj| block }] => true or false
923 * Passes each element of the collection to the given block. The method
924 * returns <code>true</code> if the block returns <code>true</code>
925 * exactly once. If the block is not given, <code>one?</code> will return
926 * <code>true</code> only if exactly one of the collection members is
929 * %w{ant bear cat}.one? {|word| word.length == 4} #=> true
930 * %w{ant bear cat}.one? {|word| word.length > 4} #=> false
931 * %w{ant bear cat}.one? {|word| word.length < 4} #=> false
932 * [ nil, true, 99 ].one? #=> false
933 * [ nil, true, false ].one? #=> true
940 VALUE result
= Qundef
;
942 rb_block_call(obj
, id_each
, 0, 0, rb_block_given_p() ? one_iter_i
: one_i
, (VALUE
)&result
);
943 if (result
== Qundef
) return Qfalse
;
948 enum_none_func(VALUE result
, VALUE
*memo
)
957 DEFINE_ENUMFUNCS(none
)
961 * enum.none? [{|obj| block }] => true or false
963 * Passes each element of the collection to the given block. The method
964 * returns <code>true</code> if the block never returns <code>true</code>
965 * for all elements. If the block is not given, <code>none?</code> will return
966 * <code>true</code> only if none of the collection members is true.
968 * %w{ant bear cat}.none? {|word| word.length == 5} #=> true
969 * %w{ant bear cat}.none? {|word| word.length >= 4} #=> false
971 * [nil].none? #=> true
972 * [nil,false].none? #=> true
977 VALUE result
= Qtrue
;
979 rb_block_call(obj
, id_each
, 0, 0, rb_block_given_p() ? none_iter_i
: none_i
, (VALUE
)&result
);
984 min_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
990 if (*memo
== Qundef
) {
994 cmp
= rb_funcall(i
, id_cmp
, 1, *memo
);
995 if (rb_cmpint(cmp
, i
, *memo
) < 0) {
1003 min_ii(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1009 if (*memo
== Qundef
) {
1013 VALUE ary
= memo
[1];
1014 RARRAY_PTR(ary
)[0] = i
;
1015 RARRAY_PTR(ary
)[1] = *memo
;
1016 cmp
= rb_yield(ary
);
1017 if (rb_cmpint(cmp
, i
, *memo
) < 0) {
1028 * enum.min {| a,b | block } => obj
1030 * Returns the object in <i>enum</i> with the minimum value. The
1031 * first form assumes all objects implement <code>Comparable</code>;
1032 * the second uses the block to return <em>a <=> b</em>.
1034 * a = %w(albatross dog horse)
1035 * a.min #=> "albatross"
1036 * a.min {|a,b| a.length <=> b.length } #=> "dog"
1045 if (rb_block_given_p()) {
1046 result
[1] = rb_ary_new3(2, Qnil
, Qnil
);
1047 rb_block_call(obj
, id_each
, 0, 0, min_ii
, (VALUE
)result
);
1050 rb_block_call(obj
, id_each
, 0, 0, min_i
, (VALUE
)result
);
1052 if (result
[0] == Qundef
) return Qnil
;
1057 max_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1063 if (*memo
== Qundef
) {
1067 cmp
= rb_funcall(i
, id_cmp
, 1, *memo
);
1068 if (rb_cmpint(cmp
, i
, *memo
) > 0) {
1076 max_ii(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1082 if (*memo
== Qundef
) {
1086 VALUE ary
= memo
[1];
1087 RARRAY_PTR(ary
)[0] = i
;
1088 RARRAY_PTR(ary
)[1] = *memo
;
1089 cmp
= rb_yield(ary
);
1090 if (rb_cmpint(cmp
, i
, *memo
) > 0) {
1100 * enum.max {|a,b| block } => obj
1102 * Returns the object in _enum_ with the maximum value. The
1103 * first form assumes all objects implement <code>Comparable</code>;
1104 * the second uses the block to return <em>a <=> b</em>.
1106 * a = %w(albatross dog horse)
1108 * a.max {|a,b| a.length <=> b.length } #=> "albatross"
1117 if (rb_block_given_p()) {
1118 result
[1] = rb_ary_new3(2, Qnil
, Qnil
);
1119 rb_block_call(obj
, id_each
, 0, 0, max_ii
, (VALUE
)result
);
1122 rb_block_call(obj
, id_each
, 0, 0, max_i
, (VALUE
)result
);
1124 if (result
[0] == Qundef
) return Qnil
;
1129 minmax_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1135 if (memo
[0] == Qundef
) {
1140 n
= rb_cmpint(rb_funcall(i
, id_cmp
, 1, memo
[0]), i
, memo
[0]);
1144 n
= rb_cmpint(rb_funcall(i
, id_cmp
, 1, memo
[1]), i
, memo
[1]);
1153 minmax_ii(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1159 if (memo
[0] == Qundef
) {
1164 VALUE ary
= memo
[2];
1166 RARRAY_PTR(ary
)[0] = i
;
1167 RARRAY_PTR(ary
)[1] = memo
[0];
1168 n
= rb_cmpint(rb_yield(ary
), i
, memo
[0]);
1172 RARRAY_PTR(ary
)[0] = i
;
1173 RARRAY_PTR(ary
)[1] = memo
[1];
1174 n
= rb_cmpint(rb_yield(ary
), i
, memo
[1]);
1184 * enum.minmax => [min,max]
1185 * enum.minmax {|a,b| block } => [min,max]
1187 * Returns two elements array which contains the minimum and the
1188 * maximum value in the enumerable. The first form assumes all
1189 * objects implement <code>Comparable</code>; the second uses the
1190 * block to return <em>a <=> b</em>.
1192 * a = %w(albatross dog horse)
1193 * a.minmax #=> ["albatross", "horse"]
1194 * a.minmax {|a,b| a.length <=> b.length } #=> ["dog", "albatross"]
1198 enum_minmax(VALUE obj
)
1201 VALUE ary
= rb_ary_new3(2, Qnil
, Qnil
);
1204 if (rb_block_given_p()) {
1206 rb_block_call(obj
, id_each
, 0, 0, minmax_ii
, (VALUE
)result
);
1209 rb_block_call(obj
, id_each
, 0, 0, minmax_i
, (VALUE
)result
);
1211 if (result
[0] != Qundef
) {
1212 RARRAY_PTR(ary
)[0] = result
[0];
1213 RARRAY_PTR(ary
)[1] = result
[1];
1219 min_by_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1226 if (memo
[0] == Qundef
) {
1230 else if (rb_cmpint(rb_funcall(v
, id_cmp
, 1, memo
[0]), v
, memo
[0]) < 0) {
1239 * enum.min_by {| obj| block } => obj
1241 * Returns the object in <i>enum</i> that gives the minimum
1242 * value from the given block.
1244 * a = %w(albatross dog horse)
1245 * a.min_by {|x| x.length } #=> "dog"
1249 enum_min_by(VALUE obj
)
1253 RETURN_ENUMERATOR(obj
, 0, 0);
1257 rb_block_call(obj
, id_each
, 0, 0, min_by_i
, (VALUE
)memo
);
1262 max_by_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1269 if (memo
[0] == Qundef
) {
1273 else if (rb_cmpint(rb_funcall(v
, id_cmp
, 1, memo
[0]), v
, memo
[0]) > 0) {
1282 * enum.max_by {| obj| block } => obj
1284 * Returns the object in <i>enum</i> that gives the maximum
1285 * value from the given block.
1287 * a = %w(albatross dog horse)
1288 * a.max_by {|x| x.length } #=> "albatross"
1292 enum_max_by(VALUE obj
)
1296 RETURN_ENUMERATOR(obj
, 0, 0);
1300 rb_block_call(obj
, id_each
, 0, 0, max_by_i
, (VALUE
)memo
);
1305 minmax_by_i(VALUE i
, VALUE
*memo
, int argc
, VALUE
*argv
)
1312 if (memo
[0] == Qundef
) {
1319 if (rb_cmpint(rb_funcall(v
, id_cmp
, 1, memo
[0]), v
, memo
[0]) < 0) {
1323 if (rb_cmpint(rb_funcall(v
, id_cmp
, 1, memo
[1]), v
, memo
[1]) > 0) {
1333 * enum.minmax_by {| obj| block } => [min, max]
1335 * Returns two elements array array containing the objects in
1336 * <i>enum</i> that gives the minimum and maximum values respectively
1337 * from the given block.
1339 * a = %w(albatross dog horse)
1340 * a.minmax_by {|x| x.length } #=> ["dog", "albatross"]
1344 enum_minmax_by(VALUE obj
)
1348 RETURN_ENUMERATOR(obj
, 0, 0);
1354 rb_block_call(obj
, id_each
, 0, 0, minmax_by_i
, (VALUE
)memo
);
1355 return rb_assoc_new(memo
[2], memo
[3]);
1359 member_i(VALUE iter
, VALUE
*memo
, int argc
, VALUE
*argv
)
1361 if (rb_equal(enum_values_pack(argc
, argv
), memo
[0])) {
1370 * enum.include?(obj) => true or false
1371 * enum.member?(obj) => true or false
1373 * Returns <code>true</code> if any member of <i>enum</i> equals
1374 * <i>obj</i>. Equality is tested using <code>==</code>.
1376 * IO.constants.include? :SEEK_SET #=> true
1377 * IO.constants.include? :SEEK_NO_FURTHER #=> false
1382 enum_member(VALUE obj
, VALUE val
)
1388 rb_block_call(obj
, id_each
, 0, 0, member_i
, (VALUE
)memo
);
1393 each_with_index_i(VALUE i
, VALUE memo
, int argc
, VALUE
*argv
)
1395 long n
= (*(VALUE
*)memo
)++;
1397 return rb_yield_values(2, enum_values_pack(argc
, argv
), INT2NUM(n
));
1402 * enum.each_with_index {|obj, i| block } -> enum
1404 * Calls <em>block</em> with two arguments, the item and its index,
1405 * for each item in <i>enum</i>. Given arguments are passed through
1409 * %w(cat dog wombat).each_with_index {|item, index|
1410 * hash[item] = index
1412 * hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
1417 enum_each_with_index(int argc
, VALUE
*argv
, VALUE obj
)
1421 RETURN_ENUMERATOR(obj
, argc
, argv
);
1424 rb_block_call(obj
, id_each
, argc
, argv
, each_with_index_i
, (VALUE
)&memo
);
1431 * enum.reverse_each {|item| block }
1433 * Traverses <i>enum</i> in reverse order.
1437 enum_reverse_each(int argc
, VALUE
*argv
, VALUE obj
)
1442 RETURN_ENUMERATOR(obj
, argc
, argv
);
1444 ary
= enum_to_a(argc
, argv
, obj
);
1446 for (i
= RARRAY_LEN(ary
); --i
>= 0; ) {
1447 rb_yield(RARRAY_PTR(ary
)[i
]);
1455 zip_ary(VALUE val
, NODE
*memo
, int argc
, VALUE
*argv
)
1457 volatile VALUE result
= memo
->u1
.value
;
1458 volatile VALUE args
= memo
->u2
.value
;
1459 int n
= memo
->u3
.cnt
++;
1463 tmp
= rb_ary_new2(RARRAY_LEN(args
) + 1);
1464 rb_ary_store(tmp
, 0, enum_values_pack(argc
, argv
));
1465 for (i
=0; i
<RARRAY_LEN(args
); i
++) {
1466 VALUE e
= RARRAY_PTR(args
)[i
];
1468 if (RARRAY_LEN(e
) <= n
) {
1469 rb_ary_push(tmp
, Qnil
);
1472 rb_ary_push(tmp
, RARRAY_PTR(e
)[n
]);
1475 if (NIL_P(result
)) {
1479 rb_ary_push(result
, tmp
);
1487 return v
[0] = rb_funcall(v
[1], id_next
, 0, 0);
1493 return v
[0] = Qundef
;
1497 zip_i(VALUE val
, NODE
*memo
, int argc
, VALUE
*argv
)
1499 volatile VALUE result
= memo
->u1
.value
;
1500 volatile VALUE args
= memo
->u2
.value
;
1504 tmp
= rb_ary_new2(RARRAY_LEN(args
) + 1);
1505 rb_ary_store(tmp
, 0, enum_values_pack(argc
, argv
));
1506 for (i
=0; i
<RARRAY_LEN(args
); i
++) {
1507 if (NIL_P(RARRAY_PTR(args
)[i
])) {
1508 rb_ary_push(tmp
, Qnil
);
1513 v
[1] = RARRAY_PTR(args
)[i
];
1514 rb_rescue2(call_next
, (VALUE
)v
, call_stop
, (VALUE
)v
, rb_eStopIteration
, 0);
1515 if (v
[0] == Qundef
) {
1516 RARRAY_PTR(args
)[i
] = Qnil
;
1519 rb_ary_push(tmp
, v
[0]);
1522 if (NIL_P(result
)) {
1526 rb_ary_push(result
, tmp
);
1533 * enum.zip(arg, ...) => enumerator
1534 * enum.zip(arg, ...) {|arr| block } => nil
1536 * Takes one element from <i>enum</i> and merges corresponding
1537 * elements from each <i>args</i>. This generates a sequence of
1538 * <em>n</em>-element arrays, where <em>n</em> is one more than the
1539 * count of arguments. The length of the resulting sequence will be
1540 * <code>enum#size</code. If the size of any argument is less than
1541 * <code>enum#size</code>, <code>nil</code> values are supplied. If
1542 * a block is given, it is invoked for each output array, otherwise
1543 * an array of arrays is returned.
1548 * [1,2,3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
1549 * [1,2].zip(a,b) #=> [[1, 4, 7], [2, 5, 8]]
1550 * a.zip([1,2],[8]) #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
1555 enum_zip(int argc
, VALUE
*argv
, VALUE obj
)
1560 VALUE result
= Qnil
;
1563 for (i
=0; i
<argc
; i
++) {
1564 if (TYPE(argv
[i
]) != T_ARRAY
) {
1570 CONST_ID(conv
, "to_enum");
1571 for (i
=0; i
<argc
; i
++) {
1572 argv
[i
] = rb_funcall(argv
[i
], conv
, 1, ID2SYM(id_each
));
1575 if (!rb_block_given_p()) {
1576 result
= rb_ary_new();
1578 /* use NODE_DOT2 as memo(v, v, -) */
1579 memo
= rb_node_newnode(NODE_DOT2
, result
, rb_ary_new4(argc
, argv
), 0);
1580 rb_block_call(obj
, id_each
, 0, 0, allary
? zip_ary
: zip_i
, (VALUE
)memo
);
1586 take_i(VALUE i
, VALUE
*arg
, int argc
, VALUE
*argv
)
1588 if (arg
[1]-- == 0) rb_iter_break();
1589 rb_ary_push(arg
[0], enum_values_pack(argc
, argv
));
1595 * enum.take(n) => array
1597 * Returns first n elements from <i>enum</i>.
1599 * a = [1, 2, 3, 4, 5, 0]
1600 * a.take(3) # => [1, 2, 3]
1605 enum_take(VALUE obj
, VALUE n
)
1608 long len
= NUM2LONG(n
);
1611 rb_raise(rb_eArgError
, "attempt to take negative size");
1615 args
[0] = rb_ary_new();
1616 rb_block_call(obj
, id_each
, 0, 0, take_i
, (VALUE
)args
);
1622 take_while_i(VALUE i
, VALUE
*ary
, int argc
, VALUE
*argv
)
1624 if (!RTEST(enum_yield(argc
, argv
))) rb_iter_break();
1625 rb_ary_push(*ary
, enum_values_pack(argc
, argv
));
1631 * enum.take_while {|arr| block } => array
1633 * Passes elements to the block until the block returns nil or false,
1634 * then stops iterating and returns an array of all prior elements.
1636 * a = [1, 2, 3, 4, 5, 0]
1637 * a.take_while {|i| i < 3 } # => [1, 2]
1642 enum_take_while(VALUE obj
)
1646 RETURN_ENUMERATOR(obj
, 0, 0);
1648 rb_block_call(obj
, id_each
, 0, 0, take_while_i
, (VALUE
)&ary
);
1653 drop_i(VALUE i
, VALUE
*arg
, int argc
, VALUE
*argv
)
1656 rb_ary_push(arg
[0], enum_values_pack(argc
, argv
));
1666 * enum.drop(n) => array
1668 * Drops first n elements from <i>enum</i>, and returns rest elements
1671 * a = [1, 2, 3, 4, 5, 0]
1672 * a.drop(3) # => [4, 5, 0]
1677 enum_drop(VALUE obj
, VALUE n
)
1680 long len
= NUM2LONG(n
);
1683 rb_raise(rb_eArgError
, "attempt to drop negative size");
1687 args
[0] = rb_ary_new();
1688 rb_block_call(obj
, id_each
, 0, 0, drop_i
, (VALUE
)args
);
1694 drop_while_i(VALUE i
, VALUE
*args
, int argc
, VALUE
*argv
)
1698 if (!args
[1] && !RTEST(rb_yield(i
))) {
1702 rb_ary_push(args
[0], i
);
1709 * enum.drop_while {|arr| block } => array
1711 * Drops elements up to, but not including, the first element for
1712 * which the block returns nil or false and returns an array
1713 * containing the remaining elements.
1715 * a = [1, 2, 3, 4, 5, 0]
1716 * a.drop_while {|i| i < 3 } # => [3, 4, 5, 0]
1721 enum_drop_while(VALUE obj
)
1725 RETURN_ENUMERATOR(obj
, 0, 0);
1726 args
[0] = rb_ary_new();
1728 rb_block_call(obj
, id_each
, 0, 0, drop_while_i
, (VALUE
)args
);
1733 cycle_i(VALUE i
, VALUE ary
, int argc
, VALUE
*argv
)
1737 rb_ary_push(ary
, i
);
1744 * enum.cycle {|obj| block }
1745 * enum.cycle(n) {|obj| block }
1747 * Calls <i>block</i> for each element of <i>enum</i> repeatedly _n_
1748 * times or forever if none or nil is given. If a non-positive
1749 * number is given or the collection is empty, does nothing. Returns
1750 * nil if the loop has finished without getting interrupted.
1752 * Enumerable#cycle saves elements in an internal array so changes
1753 * to <i>enum</i> after the first pass have no effect.
1755 * a = ["a", "b", "c"]
1756 * a.cycle {|x| puts x } # print, a, b, c, a, b, c,.. forever.
1757 * a.cycle(2) {|x| puts x } # print, a, b, c, a, b, c.
1762 enum_cycle(int argc
, VALUE
*argv
, VALUE obj
)
1768 rb_scan_args(argc
, argv
, "01", &nv
);
1770 RETURN_ENUMERATOR(obj
, argc
, argv
);
1776 if (n
<= 0) return Qnil
;
1779 RBASIC(ary
)->klass
= 0;
1780 rb_block_call(obj
, id_each
, 0, 0, cycle_i
, ary
);
1781 len
= RARRAY_LEN(ary
);
1782 if (len
== 0) return Qnil
;
1783 while (n
< 0 || 0 < --n
) {
1784 for (i
=0; i
<len
; i
++) {
1785 rb_yield(RARRAY_PTR(ary
)[i
]);
1788 return Qnil
; /* not reached */
1792 * The <code>Enumerable</code> mixin provides collection classes with
1793 * several traversal and searching methods, and with the ability to
1794 * sort. The class must provide a method <code>each</code>, which
1795 * yields successive members of the collection. If
1796 * <code>Enumerable#max</code>, <code>#min</code>, or
1797 * <code>#sort</code> is used, the objects in the collection must also
1798 * implement a meaningful <code><=></code> operator, as these methods
1799 * rely on an ordering between members of the collection.
1803 Init_Enumerable(void)
1806 #define rb_intern(str) rb_intern_const(str)
1808 rb_mEnumerable
= rb_define_module("Enumerable");
1810 rb_define_method(rb_mEnumerable
, "to_a", enum_to_a
, -1);
1811 rb_define_method(rb_mEnumerable
, "entries", enum_to_a
, -1);
1813 rb_define_method(rb_mEnumerable
, "sort", enum_sort
, 0);
1814 rb_define_method(rb_mEnumerable
, "sort_by", enum_sort_by
, 0);
1815 rb_define_method(rb_mEnumerable
, "grep", enum_grep
, 1);
1816 rb_define_method(rb_mEnumerable
, "count", enum_count
, -1);
1817 rb_define_method(rb_mEnumerable
, "find", enum_find
, -1);
1818 rb_define_method(rb_mEnumerable
, "detect", enum_find
, -1);
1819 rb_define_method(rb_mEnumerable
, "find_index", enum_find_index
, -1);
1820 rb_define_method(rb_mEnumerable
, "find_all", enum_find_all
, 0);
1821 rb_define_method(rb_mEnumerable
, "select", enum_find_all
, 0);
1822 rb_define_method(rb_mEnumerable
, "reject", enum_reject
, 0);
1823 rb_define_method(rb_mEnumerable
, "collect", enum_collect
, 0);
1824 rb_define_method(rb_mEnumerable
, "map", enum_collect
, 0);
1825 rb_define_method(rb_mEnumerable
, "inject", enum_inject
, -1);
1826 rb_define_method(rb_mEnumerable
, "reduce", enum_inject
, -1);
1827 rb_define_method(rb_mEnumerable
, "partition", enum_partition
, 0);
1828 rb_define_method(rb_mEnumerable
, "group_by", enum_group_by
, 0);
1829 rb_define_method(rb_mEnumerable
, "first", enum_first
, -1);
1830 rb_define_method(rb_mEnumerable
, "all?", enum_all
, 0);
1831 rb_define_method(rb_mEnumerable
, "any?", enum_any
, 0);
1832 rb_define_method(rb_mEnumerable
, "one?", enum_one
, 0);
1833 rb_define_method(rb_mEnumerable
, "none?", enum_none
, 0);
1834 rb_define_method(rb_mEnumerable
, "min", enum_min
, 0);
1835 rb_define_method(rb_mEnumerable
, "max", enum_max
, 0);
1836 rb_define_method(rb_mEnumerable
, "minmax", enum_minmax
, 0);
1837 rb_define_method(rb_mEnumerable
, "min_by", enum_min_by
, 0);
1838 rb_define_method(rb_mEnumerable
, "max_by", enum_max_by
, 0);
1839 rb_define_method(rb_mEnumerable
, "minmax_by", enum_minmax_by
, 0);
1840 rb_define_method(rb_mEnumerable
, "member?", enum_member
, 1);
1841 rb_define_method(rb_mEnumerable
, "include?", enum_member
, 1);
1842 rb_define_method(rb_mEnumerable
, "each_with_index", enum_each_with_index
, -1);
1843 rb_define_method(rb_mEnumerable
, "reverse_each", enum_reverse_each
, -1);
1844 rb_define_method(rb_mEnumerable
, "zip", enum_zip
, -1);
1845 rb_define_method(rb_mEnumerable
, "take", enum_take
, 1);
1846 rb_define_method(rb_mEnumerable
, "take_while", enum_take_while
, 0);
1847 rb_define_method(rb_mEnumerable
, "drop", enum_drop
, 1);
1848 rb_define_method(rb_mEnumerable
, "drop_while", enum_drop_while
, 0);
1849 rb_define_method(rb_mEnumerable
, "cycle", enum_cycle
, -1);
1851 id_eqq
= rb_intern("===");
1852 id_each
= rb_intern("each");
1853 id_cmp
= rb_intern("<=>");
1854 id_next
= rb_intern("next");
1855 id_size
= rb_intern("size");