[ruby/win32ole] Undefine allocator of WIN32OLE_VARIABLE to get rid of warning
[ruby-80x24.org.git] / enum.c
blobf8e327ff7f5dbf3b64d99fa6733b8239ffada78b
1 /**********************************************************************
3 enum.c -
5 $Author$
6 created at: Fri Oct 1 15:15:19 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "id.h"
13 #include "internal.h"
14 #include "internal/compar.h"
15 #include "internal/enum.h"
16 #include "internal/hash.h"
17 #include "internal/imemo.h"
18 #include "internal/numeric.h"
19 #include "internal/object.h"
20 #include "internal/proc.h"
21 #include "internal/rational.h"
22 #include "internal/re.h"
23 #include "ruby/util.h"
24 #include "ruby_assert.h"
25 #include "symbol.h"
27 VALUE rb_mEnumerable;
29 static ID id_next;
30 static ID id__alone;
31 static ID id__separator;
32 static ID id_chunk_categorize;
33 static ID id_chunk_enumerable;
34 static ID id_sliceafter_enum;
35 static ID id_sliceafter_pat;
36 static ID id_sliceafter_pred;
37 static ID id_slicebefore_enumerable;
38 static ID id_slicebefore_sep_pat;
39 static ID id_slicebefore_sep_pred;
40 static ID id_slicewhen_enum;
41 static ID id_slicewhen_inverted;
42 static ID id_slicewhen_pred;
44 #define id_div idDiv
45 #define id_each idEach
46 #define id_eqq idEqq
47 #define id_cmp idCmp
48 #define id_lshift idLTLT
49 #define id_call idCall
50 #define id_size idSize
52 VALUE
53 rb_enum_values_pack(int argc, const VALUE *argv)
55 if (argc == 0) return Qnil;
56 if (argc == 1) return argv[0];
57 return rb_ary_new4(argc, argv);
60 #define ENUM_WANT_SVALUE() do { \
61 i = rb_enum_values_pack(argc, argv); \
62 } while (0)
64 static VALUE
65 enum_yield(int argc, VALUE ary)
67 if (argc > 1)
68 return rb_yield_force_blockarg(ary);
69 if (argc == 1)
70 return rb_yield(ary);
71 return rb_yield_values2(0, 0);
74 static VALUE
75 enum_yield_array(VALUE ary)
77 long len = RARRAY_LEN(ary);
79 if (len > 1)
80 return rb_yield_force_blockarg(ary);
81 if (len == 1)
82 return rb_yield(RARRAY_AREF(ary, 0));
83 return rb_yield_values2(0, 0);
86 static VALUE
87 grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
89 struct MEMO *memo = MEMO_CAST(args);
90 ENUM_WANT_SVALUE();
92 if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
93 rb_ary_push(memo->v2, i);
95 return Qnil;
98 static VALUE
99 grep_regexp_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
101 struct MEMO *memo = MEMO_CAST(args);
102 VALUE converted_element, match;
103 ENUM_WANT_SVALUE();
105 /* In case element can't be converted to a Symbol or String: not a match (don't raise) */
106 converted_element = SYMBOL_P(i) ? i : rb_check_string_type(i);
107 match = NIL_P(converted_element) ? Qfalse : rb_reg_match_p(memo->v1, i, 0);
108 if (match == memo->u3.value) {
109 rb_ary_push(memo->v2, i);
111 return Qnil;
114 static VALUE
115 grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
117 struct MEMO *memo = MEMO_CAST(args);
118 ENUM_WANT_SVALUE();
120 if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
121 rb_ary_push(memo->v2, enum_yield(argc, i));
123 return Qnil;
126 static VALUE
127 enum_grep0(VALUE obj, VALUE pat, VALUE test)
129 VALUE ary = rb_ary_new();
130 struct MEMO *memo = MEMO_NEW(pat, ary, test);
131 rb_block_call_func_t fn;
132 if (rb_block_given_p()) {
133 fn = grep_iter_i;
135 else if (RB_TYPE_P(pat, T_REGEXP) &&
136 LIKELY(rb_method_basic_definition_p(CLASS_OF(pat), idEqq))) {
137 fn = grep_regexp_i;
139 else {
140 fn = grep_i;
142 rb_block_call(obj, id_each, 0, 0, fn, (VALUE)memo);
144 return ary;
148 * call-seq:
149 * grep(pattern) -> array
150 * grep(pattern) {|element| ... } -> array
152 * Returns an array of objects based elements of +self+ that match the given pattern.
154 * With no block given, returns an array containing each element
155 * for which <tt>pattern === element</tt> is +true+:
157 * a = ['foo', 'bar', 'car', 'moo']
158 * a.grep(/ar/) # => ["bar", "car"]
159 * (1..10).grep(3..8) # => [3, 4, 5, 6, 7, 8]
160 * ['a', 'b', 0, 1].grep(Integer) # => [0, 1]
162 * With a block given,
163 * calls the block with each matching element and returns an array containing each
164 * object returned by the block:
166 * a = ['foo', 'bar', 'car', 'moo']
167 * a.grep(/ar/) {|element| element.upcase } # => ["BAR", "CAR"]
169 * Related: #grep_v.
172 static VALUE
173 enum_grep(VALUE obj, VALUE pat)
175 return enum_grep0(obj, pat, Qtrue);
179 * call-seq:
180 * grep_v(pattern) -> array
181 * grep_v(pattern) {|element| ... } -> array
183 * Returns an array of objects based on elements of +self+
184 * that <em>don't</em> match the given pattern.
186 * With no block given, returns an array containing each element
187 * for which <tt>pattern === element</tt> is +false+:
189 * a = ['foo', 'bar', 'car', 'moo']
190 * a.grep_v(/ar/) # => ["foo", "moo"]
191 * (1..10).grep_v(3..8) # => [1, 2, 9, 10]
192 * ['a', 'b', 0, 1].grep_v(Integer) # => ["a", "b"]
194 * With a block given,
195 * calls the block with each non-matching element and returns an array containing each
196 * object returned by the block:
198 * a = ['foo', 'bar', 'car', 'moo']
199 * a.grep_v(/ar/) {|element| element.upcase } # => ["FOO", "MOO"]
201 * Related: #grep.
204 static VALUE
205 enum_grep_v(VALUE obj, VALUE pat)
207 return enum_grep0(obj, pat, Qfalse);
210 #define COUNT_BIGNUM IMEMO_FL_USER0
211 #define MEMO_V3_SET(m, v) RB_OBJ_WRITE((m), &(m)->u3.value, (v))
213 static void
214 imemo_count_up(struct MEMO *memo)
216 if (memo->flags & COUNT_BIGNUM) {
217 MEMO_V3_SET(memo, rb_int_succ(memo->u3.value));
219 else if (++memo->u3.cnt == 0) {
220 /* overflow */
221 unsigned long buf[2] = {0, 1};
222 MEMO_V3_SET(memo, rb_big_unpack(buf, 2));
223 memo->flags |= COUNT_BIGNUM;
227 static VALUE
228 imemo_count_value(struct MEMO *memo)
230 if (memo->flags & COUNT_BIGNUM) {
231 return memo->u3.value;
233 else {
234 return ULONG2NUM(memo->u3.cnt);
238 static VALUE
239 count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
241 struct MEMO *memo = MEMO_CAST(memop);
243 ENUM_WANT_SVALUE();
245 if (rb_equal(i, memo->v1)) {
246 imemo_count_up(memo);
248 return Qnil;
251 static VALUE
252 count_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
254 struct MEMO *memo = MEMO_CAST(memop);
256 if (RTEST(rb_yield_values2(argc, argv))) {
257 imemo_count_up(memo);
259 return Qnil;
262 static VALUE
263 count_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
265 struct MEMO *memo = MEMO_CAST(memop);
267 imemo_count_up(memo);
268 return Qnil;
272 * call-seq:
273 * count -> integer
274 * count(object) -> integer
275 * count {|element| ... } -> integer
277 * Returns the count of elements, based on an argument or block criterion, if given.
279 * With no argument and no block given, returns the number of elements:
281 * [0, 1, 2].count # => 3
282 * {foo: 0, bar: 1, baz: 2}.count # => 3
284 * With argument +object+ given,
285 * returns the number of elements that are <tt>==</tt> to +object+:
287 * [0, 1, 2, 1].count(1) # => 2
289 * With a block given, calls the block with each element
290 * and returns the number of elements for which the block returns a truthy value:
292 * [0, 1, 2, 3].count {|element| element < 2} # => 2
293 * {foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
297 static VALUE
298 enum_count(int argc, VALUE *argv, VALUE obj)
300 VALUE item = Qnil;
301 struct MEMO *memo;
302 rb_block_call_func *func;
304 if (argc == 0) {
305 if (rb_block_given_p()) {
306 func = count_iter_i;
308 else {
309 func = count_all_i;
312 else {
313 rb_scan_args(argc, argv, "1", &item);
314 if (rb_block_given_p()) {
315 rb_warn("given block not used");
317 func = count_i;
320 memo = MEMO_NEW(item, 0, 0);
321 rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
322 return imemo_count_value(memo);
325 static VALUE
326 find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
328 ENUM_WANT_SVALUE();
330 if (RTEST(enum_yield(argc, i))) {
331 struct MEMO *memo = MEMO_CAST(memop);
332 MEMO_V1_SET(memo, i);
333 memo->u3.cnt = 1;
334 rb_iter_break();
336 return Qnil;
340 * call-seq:
341 * find(if_none_proc = nil) {|element| ... } -> object or nil
342 * find(if_none_proc = nil) -> enumerator
344 * Returns the first element for which the block returns a truthy value.
346 * With a block given, calls the block with successive elements of the collection;
347 * returns the first element for which the block returns a truthy value:
349 * (0..9).find {|element| element > 2} # => 3
351 * If no such element is found, calls +if_none_proc+ and returns its return value.
353 * (0..9).find(proc {false}) {|element| element > 12} # => false
354 * {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1]
355 * {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
357 * With no block given, returns an \Enumerator.
360 static VALUE
361 enum_find(int argc, VALUE *argv, VALUE obj)
363 struct MEMO *memo;
364 VALUE if_none;
366 if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
367 RETURN_ENUMERATOR(obj, argc, argv);
368 memo = MEMO_NEW(Qundef, 0, 0);
369 rb_block_call(obj, id_each, 0, 0, find_i, (VALUE)memo);
370 if (memo->u3.cnt) {
371 return memo->v1;
373 if (!NIL_P(if_none)) {
374 return rb_funcallv(if_none, id_call, 0, 0);
376 return Qnil;
379 static VALUE
380 find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
382 struct MEMO *memo = MEMO_CAST(memop);
384 ENUM_WANT_SVALUE();
386 if (rb_equal(i, memo->v2)) {
387 MEMO_V1_SET(memo, imemo_count_value(memo));
388 rb_iter_break();
390 imemo_count_up(memo);
391 return Qnil;
394 static VALUE
395 find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
397 struct MEMO *memo = MEMO_CAST(memop);
399 if (RTEST(rb_yield_values2(argc, argv))) {
400 MEMO_V1_SET(memo, imemo_count_value(memo));
401 rb_iter_break();
403 imemo_count_up(memo);
404 return Qnil;
408 * call-seq:
409 * find_index(object) -> integer or nil
410 * find_index {|element| ... } -> integer or nil
411 * find_index -> enumerator
413 * Returns the index of the first element that meets a specified criterion,
414 * or +nil+ if no such element is found.
416 * With argument +object+ given,
417 * returns the index of the first element that is <tt>==</tt> +object+:
419 * ['a', 'b', 'c', 'b'].find_index('b') # => 1
421 * With a block given, calls the block with successive elements;
422 * returns the first element for which the block returns a truthy value:
424 * ['a', 'b', 'c', 'b'].find_index {|element| element.start_with?('b') } # => 1
425 * {foo: 0, bar: 1, baz: 2}.find_index {|key, value| value > 1 } # => 2
427 * With no argument and no block given, returns an \Enumerator.
431 static VALUE
432 enum_find_index(int argc, VALUE *argv, VALUE obj)
434 struct MEMO *memo; /* [return value, current index, ] */
435 VALUE condition_value = Qnil;
436 rb_block_call_func *func;
438 if (argc == 0) {
439 RETURN_ENUMERATOR(obj, 0, 0);
440 func = find_index_iter_i;
442 else {
443 rb_scan_args(argc, argv, "1", &condition_value);
444 if (rb_block_given_p()) {
445 rb_warn("given block not used");
447 func = find_index_i;
450 memo = MEMO_NEW(Qnil, condition_value, 0);
451 rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
452 return memo->v1;
455 static VALUE
456 find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
458 ENUM_WANT_SVALUE();
460 if (RTEST(enum_yield(argc, i))) {
461 rb_ary_push(ary, i);
463 return Qnil;
466 static VALUE
467 enum_size(VALUE self, VALUE args, VALUE eobj)
469 return rb_check_funcall_default(self, id_size, 0, 0, Qnil);
472 static long
473 limit_by_enum_size(VALUE obj, long n)
475 unsigned long limit;
476 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
477 if (!FIXNUM_P(size)) return n;
478 limit = FIX2ULONG(size);
479 return ((unsigned long)n > limit) ? (long)limit : n;
482 static int
483 enum_size_over_p(VALUE obj, long n)
485 VALUE size = rb_check_funcall(obj, id_size, 0, 0);
486 if (!FIXNUM_P(size)) return 0;
487 return ((unsigned long)n > FIX2ULONG(size));
491 * call-seq:
492 * select {|element| ... } -> array
493 * select -> enumerator
495 * Returns an array containing elements selected by the block.
497 * With a block given, calls the block with successive elements;
498 * returns an array of those elements for which the block returns a truthy value:
500 * (0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9]
501 * a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') }
502 * a # => {:bar=>1, :baz=>2}
504 * With no block given, returns an \Enumerator.
506 * Related: #reject.
508 static VALUE
509 enum_find_all(VALUE obj)
511 VALUE ary;
513 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
515 ary = rb_ary_new();
516 rb_block_call(obj, id_each, 0, 0, find_all_i, ary);
518 return ary;
521 static VALUE
522 filter_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
524 i = rb_yield_values2(argc, argv);
526 if (RTEST(i)) {
527 rb_ary_push(ary, i);
530 return Qnil;
534 * call-seq:
535 * filter_map {|element| ... } -> array
536 * filter_map -> enumerator
538 * Returns an array containing truthy elements returned by the block.
540 * With a block given, calls the block with successive elements;
541 * returns an array containing each truthy value returned by the block:
543 * (0..9).filter_map {|i| i * 2 if i.even? } # => [0, 4, 8, 12, 16]
544 * {foo: 0, bar: 1, baz: 2}.filter_map {|key, value| key if value.even? } # => [:foo, :baz]
546 * When no block given, returns an \Enumerator.
549 static VALUE
550 enum_filter_map(VALUE obj)
552 VALUE ary;
554 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
556 ary = rb_ary_new();
557 rb_block_call(obj, id_each, 0, 0, filter_map_i, ary);
559 return ary;
563 static VALUE
564 reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
566 ENUM_WANT_SVALUE();
568 if (!RTEST(enum_yield(argc, i))) {
569 rb_ary_push(ary, i);
571 return Qnil;
575 * call-seq:
576 * reject {|element| ... } -> array
577 * reject -> enumerator
579 * Returns an array of objects rejected by the block.
581 * With a block given, calls the block with successive elements;
582 * returns an array of those elements for which the block returns +nil+ or +false+:
584 * (0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9]
585 * {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
587 * When no block given, returns an \Enumerator.
589 * Related: #select.
592 static VALUE
593 enum_reject(VALUE obj)
595 VALUE ary;
597 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
599 ary = rb_ary_new();
600 rb_block_call(obj, id_each, 0, 0, reject_i, ary);
602 return ary;
605 static VALUE
606 collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
608 rb_ary_push(ary, rb_yield_values2(argc, argv));
610 return Qnil;
613 static VALUE
614 collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
616 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
618 return Qnil;
622 * call-seq:
623 * map {|element| ... } -> array
624 * map -> enumerator
626 * Returns an array of objects returned by the block.
628 * With a block given, calls the block with successive elements;
629 * returns an array of the objects returned by the block:
631 * (0..4).map {|i| i*i } # => [0, 1, 4, 9, 16]
632 * {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
634 * With no block given, returns an \Enumerator.
637 static VALUE
638 enum_collect(VALUE obj)
640 VALUE ary;
641 int min_argc, max_argc;
643 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
645 ary = rb_ary_new();
646 min_argc = rb_block_min_max_arity(&max_argc);
647 rb_lambda_call(obj, id_each, 0, 0, collect_i, min_argc, max_argc, ary);
649 return ary;
652 static VALUE
653 flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
655 VALUE tmp;
657 i = rb_yield_values2(argc, argv);
658 tmp = rb_check_array_type(i);
660 if (NIL_P(tmp)) {
661 rb_ary_push(ary, i);
663 else {
664 rb_ary_concat(ary, tmp);
666 return Qnil;
670 * call-seq:
671 * flat_map {|element| ... } -> array
672 * flat_map -> enumerator
674 * Returns an array of flattened objects returned by the block.
676 * With a block given, calls the block with successive elements;
677 * returns a flattened array of objects returned by the block:
679 * [0, 1, 2, 3].flat_map {|element| -element } # => [0, -1, -2, -3]
680 * [0, 1, 2, 3].flat_map {|element| [element, -element] } # => [0, 0, 1, -1, 2, -2, 3, -3]
681 * [[0, 1], [2, 3]].flat_map {|e| e + [100] } # => [0, 1, 100, 2, 3, 100]
682 * {foo: 0, bar: 1, baz: 2}.flat_map {|key, value| [key, value] } # => [:foo, 0, :bar, 1, :baz, 2]
684 * With no block given, returns an \Enumerator.
686 * Alias: #collect_concat.
688 static VALUE
689 enum_flat_map(VALUE obj)
691 VALUE ary;
693 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
695 ary = rb_ary_new();
696 rb_block_call(obj, id_each, 0, 0, flat_map_i, ary);
698 return ary;
702 * call-seq:
703 * to_a -> array
705 * Returns an array containing the items in +self+:
707 * (0..4).to_a # => [0, 1, 2, 3, 4]
709 * Enumerable#entries is an alias for Enumerable#to_a.
711 static VALUE
712 enum_to_a(int argc, VALUE *argv, VALUE obj)
714 VALUE ary = rb_ary_new();
716 rb_block_call_kw(obj, id_each, argc, argv, collect_all, ary, RB_PASS_CALLED_KEYWORDS);
718 return ary;
721 static VALUE
722 enum_hashify_into(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter, VALUE hash)
724 rb_block_call(obj, id_each, argc, argv, iter, hash);
725 return hash;
728 static VALUE
729 enum_hashify(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter)
731 return enum_hashify_into(obj, argc, argv, iter, rb_hash_new());
734 static VALUE
735 enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
737 ENUM_WANT_SVALUE();
738 return rb_hash_set_pair(hash, i);
741 static VALUE
742 enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
744 return rb_hash_set_pair(hash, rb_yield_values2(argc, argv));
748 * call-seq:
749 * to_h -> hash
750 * to_h {|element| ... } -> hash
752 * When +self+ consists of 2-element arrays,
753 * returns a hash each of whose entries is the key-value pair
754 * formed from one of those arrays:
756 * [[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
758 * When a block is given, the block is called with each element of +self+;
759 * the block should return a 2-element array which becomes a key-value pair
760 * in the returned hash:
762 * (0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
764 * Raises an exception if an element of +self+ is not a 2-element array,
765 * and a block is not passed.
768 static VALUE
769 enum_to_h(int argc, VALUE *argv, VALUE obj)
771 rb_block_call_func *iter = rb_block_given_p() ? enum_to_h_ii : enum_to_h_i;
772 return enum_hashify(obj, argc, argv, iter);
775 static VALUE
776 inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
778 struct MEMO *memo = MEMO_CAST(p);
780 ENUM_WANT_SVALUE();
782 if (memo->v1 == Qundef) {
783 MEMO_V1_SET(memo, i);
785 else {
786 MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i));
788 return Qnil;
791 static VALUE
792 inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
794 struct MEMO *memo = MEMO_CAST(p);
795 VALUE name;
797 ENUM_WANT_SVALUE();
799 if (memo->v1 == Qundef) {
800 MEMO_V1_SET(memo, i);
802 else if (SYMBOL_P(name = memo->u3.value)) {
803 const ID mid = SYM2ID(name);
804 MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i));
806 else {
807 VALUE args[2];
808 args[0] = name;
809 args[1] = i;
810 MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1));
812 return Qnil;
815 static VALUE
816 ary_inject_op(VALUE ary, VALUE init, VALUE op)
818 ID id;
819 VALUE v, e;
820 long i, n;
822 if (RARRAY_LEN(ary) == 0)
823 return init == Qundef ? Qnil : init;
825 if (init == Qundef) {
826 v = RARRAY_AREF(ary, 0);
827 i = 1;
828 if (RARRAY_LEN(ary) == 1)
829 return v;
831 else {
832 v = init;
833 i = 0;
836 id = SYM2ID(op);
837 if (id == idPLUS) {
838 if (RB_INTEGER_TYPE_P(v) &&
839 rb_method_basic_definition_p(rb_cInteger, idPLUS) &&
840 rb_obj_respond_to(v, idPLUS, FALSE)) {
841 n = 0;
842 for (; i < RARRAY_LEN(ary); i++) {
843 e = RARRAY_AREF(ary, i);
844 if (FIXNUM_P(e)) {
845 n += FIX2LONG(e); /* should not overflow long type */
846 if (!FIXABLE(n)) {
847 v = rb_big_plus(LONG2NUM(n), v);
848 n = 0;
851 else if (RB_BIGNUM_TYPE_P(e))
852 v = rb_big_plus(e, v);
853 else
854 goto not_integer;
856 if (n != 0)
857 v = rb_fix_plus(LONG2FIX(n), v);
858 return v;
860 not_integer:
861 if (n != 0)
862 v = rb_fix_plus(LONG2FIX(n), v);
865 for (; i < RARRAY_LEN(ary); i++) {
866 VALUE arg = RARRAY_AREF(ary, i);
867 v = rb_funcallv_public(v, id, 1, &arg);
869 return v;
873 * call-seq:
874 * inject(symbol) -> object
875 * inject(initial_operand, symbol) -> object
876 * inject {|memo, operand| ... } -> object
877 * inject(initial_operand) {|memo, operand| ... } -> object
879 * Returns an object formed from operands via either:
881 * - A method named by +symbol+.
882 * - A block to which each operand is passed.
884 * With method-name argument +symbol+,
885 * combines operands using the method:
887 * # Sum, without initial_operand.
888 * (1..4).inject(:+) # => 10
889 * # Sum, with initial_operand.
890 * (1..4).inject(10, :+) # => 20
892 * With a block, passes each operand to the block:
894 * # Sum of squares, without initial_operand.
895 * (1..4).inject {|sum, n| sum + n*n } # => 30
896 * # Sum of squares, with initial_operand.
897 * (1..4).inject(2) {|sum, n| sum + n*n } # => 32
899 * <b>Operands</b>
901 * If argument +initial_operand+ is not given,
902 * the operands for +inject+ are simply the elements of +self+.
903 * Example calls and their operands:
905 * - <tt>(1..4).inject(:+)</tt>:: <tt>[1, 2, 3, 4]</tt>.
906 * - <tt>(1...4).inject(:+)</tt>:: <tt>[1, 2, 3]</tt>.
907 * - <tt>('a'..'d').inject(:+)</tt>:: <tt>['a', 'b', 'c', 'd']</tt>.
908 * - <tt>('a'...'d').inject(:+)</tt>:: <tt>['a', 'b', 'c']</tt>.
910 * Examples with first operand (which is <tt>self.first</tt>) of various types:
912 * # Integer.
913 * (1..4).inject(:+) # => 10
914 * # Float.
915 * [1.0, 2, 3, 4].inject(:+) # => 10.0
916 * # Character.
917 * ('a'..'d').inject(:+) # => "abcd"
918 * # Complex.
919 * [Complex(1, 2), 3, 4].inject(:+) # => (8+2i)
921 * If argument +initial_operand+ is given,
922 * the operands for +inject+ are that value plus the elements of +self+.
923 * Example calls their operands:
925 * - <tt>(1..4).inject(10, :+)</tt>:: <tt>[10, 1, 2, 3, 4]</tt>.
926 * - <tt>(1...4).inject(10, :+)</tt>:: <tt>[10, 1, 2, 3]</tt>.
927 * - <tt>('a'..'d').inject('e', :+)</tt>:: <tt>['e', 'a', 'b', 'c', 'd']</tt>.
928 * - <tt>('a'...'d').inject('e', :+)</tt>:: <tt>['e', 'a', 'b', 'c']</tt>.
930 * Examples with +initial_operand+ of various types:
932 * # Integer.
933 * (1..4).inject(2, :+) # => 12
934 * # Float.
935 * (1..4).inject(2.0, :+) # => 12.0
936 * # String.
937 * ('a'..'d').inject('foo', :+) # => "fooabcd"
938 * # Array.
939 * %w[a b c].inject(['x'], :push) # => ["x", "a", "b", "c"]
940 * # Complex.
941 * (1..4).inject(Complex(2, 2), :+) # => (12+2i)
943 * <b>Combination by Given \Method</b>
945 * If the method-name argument +symbol+ is given,
946 * the operands are combined by that method:
948 * - The first and second operands are combined.
949 * - That result is combined with the third operand.
950 * - That result is combined with the fourth operand.
951 * - And so on.
953 * The return value from +inject+ is the result of the last combination.
955 * This call to +inject+ computes the sum of the operands:
957 * (1..4).inject(:+) # => 10
959 * Examples with various methods:
961 * # Integer addition.
962 * (1..4).inject(:+) # => 10
963 * # Integer multiplication.
964 * (1..4).inject(:*) # => 24
965 * # Character range concatenation.
966 * ('a'..'d').inject('', :+) # => "abcd"
967 * # String array concatenation.
968 * %w[foo bar baz].inject('', :+) # => "foobarbaz"
969 * # Hash update.
970 * h = [{foo: 0, bar: 1}, {baz: 2}, {bat: 3}].inject(:update)
971 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
972 * # Hash conversion to nested arrays.
973 * h = {foo: 0, bar: 1}.inject([], :push)
974 * h # => [[:foo, 0], [:bar, 1]]
976 * <b>Combination by Given Block</b>
978 * If a block is given, the operands are passed to the block:
980 * - The first call passes the first and second operands.
981 * - The second call passes the result of the first call,
982 * along with the third operand.
983 * - The third call passes the result of the second call,
984 * along with the fourth operand.
985 * - And so on.
987 * The return value from +inject+ is the return value from the last block call.
989 * This call to +inject+ gives a block
990 * that writes the memo and element, and also sums the elements:
992 * (1..4).inject do |memo, element|
993 * p "Memo: #{memo}; element: #{element}"
994 * memo + element
995 * end # => 10
997 * Output:
999 * "Memo: 1; element: 2"
1000 * "Memo: 3; element: 3"
1001 * "Memo: 6; element: 4"
1003 * Enumerable#reduce is an alias for Enumerable#inject.
1006 static VALUE
1007 enum_inject(int argc, VALUE *argv, VALUE obj)
1009 struct MEMO *memo;
1010 VALUE init, op;
1011 rb_block_call_func *iter = inject_i;
1012 ID id;
1014 switch (rb_scan_args(argc, argv, "02", &init, &op)) {
1015 case 0:
1016 init = Qundef;
1017 break;
1018 case 1:
1019 if (rb_block_given_p()) {
1020 break;
1022 id = rb_check_id(&init);
1023 op = id ? ID2SYM(id) : init;
1024 init = Qundef;
1025 iter = inject_op_i;
1026 break;
1027 case 2:
1028 if (rb_block_given_p()) {
1029 rb_warning("given block not used");
1031 id = rb_check_id(&op);
1032 if (id) op = ID2SYM(id);
1033 iter = inject_op_i;
1034 break;
1037 if (iter == inject_op_i &&
1038 SYMBOL_P(op) &&
1039 RB_TYPE_P(obj, T_ARRAY) &&
1040 rb_method_basic_definition_p(CLASS_OF(obj), id_each)) {
1041 return ary_inject_op(obj, init, op);
1044 memo = MEMO_NEW(init, Qnil, op);
1045 rb_block_call(obj, id_each, 0, 0, iter, (VALUE)memo);
1046 if (memo->v1 == Qundef) return Qnil;
1047 return memo->v1;
1050 static VALUE
1051 partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arys))
1053 struct MEMO *memo = MEMO_CAST(arys);
1054 VALUE ary;
1055 ENUM_WANT_SVALUE();
1057 if (RTEST(enum_yield(argc, i))) {
1058 ary = memo->v1;
1060 else {
1061 ary = memo->v2;
1063 rb_ary_push(ary, i);
1064 return Qnil;
1068 * call-seq:
1069 * partition {|element| ... } -> [true_array, false_array]
1070 * partition -> enumerator
1072 * With a block given, returns an array of two arrays:
1074 * - The first having those elements for which the block returns a truthy value.
1075 * - The other having all other elements.
1077 * Examples:
1079 * p = (1..4).partition {|i| i.even? }
1080 * p # => [[2, 4], [1, 3]]
1081 * p = ('a'..'d').partition {|c| c < 'c' }
1082 * p # => [["a", "b"], ["c", "d"]]
1083 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
1084 * p = h.partition {|key, value| key.start_with?('b') }
1085 * p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
1086 * p = h.partition {|key, value| value < 2 }
1087 * p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]
1089 * With no block given, returns an Enumerator.
1091 * Related: Enumerable#group_by.
1095 static VALUE
1096 enum_partition(VALUE obj)
1098 struct MEMO *memo;
1100 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1102 memo = MEMO_NEW(rb_ary_new(), rb_ary_new(), 0);
1103 rb_block_call(obj, id_each, 0, 0, partition_i, (VALUE)memo);
1105 return rb_assoc_new(memo->v1, memo->v2);
1108 static VALUE
1109 group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
1111 VALUE group;
1112 VALUE values;
1114 ENUM_WANT_SVALUE();
1116 group = enum_yield(argc, i);
1117 values = rb_hash_aref(hash, group);
1118 if (!RB_TYPE_P(values, T_ARRAY)) {
1119 values = rb_ary_new3(1, i);
1120 rb_hash_aset(hash, group, values);
1122 else {
1123 rb_ary_push(values, i);
1125 return Qnil;
1129 * call-seq:
1130 * group_by {|element| ... } -> hash
1131 * group_by -> enumerator
1133 * With a block given returns a hash:
1135 * - Each key is a return value from the block.
1136 * - Each value is an array of those elements for which the block returned that key.
1138 * Examples:
1140 * g = (1..6).group_by {|i| i%3 }
1141 * g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]}
1142 * h = {foo: 0, bar: 1, baz: 0, bat: 1}
1143 * g = h.group_by {|key, value| value }
1144 * g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
1146 * With no block given, returns an Enumerator.
1150 static VALUE
1151 enum_group_by(VALUE obj)
1153 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1155 return enum_hashify(obj, 0, 0, group_by_i);
1158 static int
1159 tally_up(st_data_t *group, st_data_t *value, st_data_t arg, int existing)
1161 VALUE tally = (VALUE)*value;
1162 VALUE hash = (VALUE)arg;
1163 if (!existing) {
1164 tally = INT2FIX(1);
1166 else if (FIXNUM_P(tally) && tally < INT2FIX(FIXNUM_MAX)) {
1167 tally += INT2FIX(1) & ~FIXNUM_FLAG;
1169 else {
1170 Check_Type(tally, T_BIGNUM);
1171 tally = rb_big_plus(tally, INT2FIX(1));
1172 RB_OBJ_WRITTEN(hash, Qundef, tally);
1174 *value = (st_data_t)tally;
1175 if (!SPECIAL_CONST_P(*group)) RB_OBJ_WRITTEN(hash, Qundef, *group);
1176 return ST_CONTINUE;
1179 static VALUE
1180 rb_enum_tally_up(VALUE hash, VALUE group)
1182 rb_hash_stlike_update(hash, group, tally_up, (st_data_t)hash);
1183 return hash;
1186 static VALUE
1187 tally_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
1189 ENUM_WANT_SVALUE();
1190 rb_enum_tally_up(hash, i);
1191 return Qnil;
1195 * call-seq:
1196 * tally -> new_hash
1197 * tally(hash) -> hash
1199 * Returns a hash containing the counts of equal elements:
1201 * - Each key is an element of +self+.
1202 * - Each value is the number elements equal to that key.
1204 * With no argument:
1206 * %w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}
1208 * With a hash argument, that hash is used for the tally (instead of a new hash),
1209 * and is returned;
1210 * this may be useful for accumulating tallies across multiple enumerables:
1212 * hash = {}
1213 * hash = %w[a c d b c a].tally(hash)
1214 * hash # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1}
1215 * hash = %w[b a z].tally(hash)
1216 * hash # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1}
1217 * hash = %w[b a m].tally(hash)
1218 * hash # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=> 1}
1222 static VALUE
1223 enum_tally(int argc, VALUE *argv, VALUE obj)
1225 VALUE hash;
1226 if (rb_check_arity(argc, 0, 1)) {
1227 hash = rb_convert_type(argv[0], T_HASH, "Hash", "to_hash");
1228 rb_check_frozen(hash);
1230 else {
1231 hash = rb_hash_new();
1234 return enum_hashify_into(obj, 0, 0, tally_i, hash);
1237 NORETURN(static VALUE first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, params)));
1238 static VALUE
1239 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, params))
1241 struct MEMO *memo = MEMO_CAST(params);
1242 ENUM_WANT_SVALUE();
1244 MEMO_V1_SET(memo, i);
1245 rb_iter_break();
1247 UNREACHABLE_RETURN(Qnil);
1250 static VALUE enum_take(VALUE obj, VALUE n);
1253 * call-seq:
1254 * first -> element or nil
1255 * first(n) -> array
1257 * Returns the first element or elements.
1259 * With no argument, returns the first element, or +nil+ if there is none:
1261 * (1..4).first # => 1
1262 * %w[a b c].first # => "a"
1263 * {foo: 1, bar: 1, baz: 2}.first # => [:foo, 1]
1264 * [].first # => nil
1266 * With integer argument +n+, returns an array
1267 * containing the first +n+ elements that exist:
1269 * (1..4).first(2) # => [1, 2]
1270 * %w[a b c d].first(3) # => ["a", "b", "c"]
1271 * %w[a b c d].first(50) # => ["a", "b", "c", "d"]
1272 * {foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]]
1273 * [].first(2) # => []
1277 static VALUE
1278 enum_first(int argc, VALUE *argv, VALUE obj)
1280 struct MEMO *memo;
1281 rb_check_arity(argc, 0, 1);
1282 if (argc > 0) {
1283 return enum_take(obj, argv[0]);
1285 else {
1286 memo = MEMO_NEW(Qnil, 0, 0);
1287 rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo);
1288 return memo->v1;
1293 * call-seq:
1294 * sort -> array
1295 * sort {|a, b| ... } -> array
1297 * Returns an array containing the sorted elements of +self+.
1298 * The ordering of equal elements is indeterminate and may be unstable.
1300 * With no block given, the sort compares
1301 * using the elements' own method <tt><=></tt>:
1303 * %w[b c a d].sort # => ["a", "b", "c", "d"]
1304 * {foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]
1306 * With a block given, comparisons in the block determine the ordering.
1307 * The block is called with two elements +a+ and +b+, and must return:
1309 * - A negative integer if <tt>a < b</tt>.
1310 * - Zero if <tt>a == b</tt>.
1311 * - A positive integer if <tt>a > b</tt>.
1313 * Examples:
1315 * a = %w[b c a d]
1316 * a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"]
1317 * h = {foo: 0, bar: 1, baz: 2}
1318 * h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]
1320 * See also #sort_by. It implements a Schwartzian transform
1321 * which is useful when key computation or comparison is expensive.
1324 static VALUE
1325 enum_sort(VALUE obj)
1327 return rb_ary_sort_bang(enum_to_a(0, 0, obj));
1330 #define SORT_BY_BUFSIZE 16
1331 struct sort_by_data {
1332 const VALUE ary;
1333 const VALUE buf;
1334 long n;
1337 static VALUE
1338 sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data))
1340 struct sort_by_data *data = (struct sort_by_data *)&MEMO_CAST(_data)->v1;
1341 VALUE ary = data->ary;
1342 VALUE v;
1344 ENUM_WANT_SVALUE();
1346 v = enum_yield(argc, i);
1348 if (RBASIC(ary)->klass) {
1349 rb_raise(rb_eRuntimeError, "sort_by reentered");
1351 if (RARRAY_LEN(data->buf) != SORT_BY_BUFSIZE*2) {
1352 rb_raise(rb_eRuntimeError, "sort_by reentered");
1355 RARRAY_ASET(data->buf, data->n*2, v);
1356 RARRAY_ASET(data->buf, data->n*2+1, i);
1357 data->n++;
1358 if (data->n == SORT_BY_BUFSIZE) {
1359 rb_ary_concat(ary, data->buf);
1360 data->n = 0;
1362 return Qnil;
1365 static int
1366 sort_by_cmp(const void *ap, const void *bp, void *data)
1368 struct cmp_opt_data cmp_opt = { 0, 0 };
1369 VALUE a;
1370 VALUE b;
1371 VALUE ary = (VALUE)data;
1373 if (RBASIC(ary)->klass) {
1374 rb_raise(rb_eRuntimeError, "sort_by reentered");
1377 a = *(VALUE *)ap;
1378 b = *(VALUE *)bp;
1380 return OPTIMIZED_CMP(a, b, cmp_opt);
1384 * call-seq:
1385 * sort_by {|element| ... } -> array
1386 * sort_by -> enumerator
1388 * With a block given, returns an array of elements of +self+,
1389 * sorted according to the value returned by the block for each element.
1390 * The ordering of equal elements is indeterminate and may be unstable.
1392 * Examples:
1394 * a = %w[xx xxx x xxxx]
1395 * a.sort_by {|s| s.size } # => ["x", "xx", "xxx", "xxxx"]
1396 * a.sort_by {|s| -s.size } # => ["xxxx", "xxx", "xx", "x"]
1397 * h = {foo: 2, bar: 1, baz: 0}
1398 * h.sort_by{|key, value| value } # => [[:baz, 0], [:bar, 1], [:foo, 2]]
1399 * h.sort_by{|key, value| key } # => [[:bar, 1], [:baz, 0], [:foo, 2]]
1401 * With no block given, returns an Enumerator.
1403 * The current implementation of #sort_by generates an array of
1404 * tuples containing the original collection element and the mapped
1405 * value. This makes #sort_by fairly expensive when the keysets are
1406 * simple.
1408 * require 'benchmark'
1410 * a = (1..100000).map { rand(100000) }
1412 * Benchmark.bm(10) do |b|
1413 * b.report("Sort") { a.sort }
1414 * b.report("Sort by") { a.sort_by { |a| a } }
1415 * end
1417 * <em>produces:</em>
1419 * user system total real
1420 * Sort 0.180000 0.000000 0.180000 ( 0.175469)
1421 * Sort by 1.980000 0.040000 2.020000 ( 2.013586)
1423 * However, consider the case where comparing the keys is a non-trivial
1424 * operation. The following code sorts some files on modification time
1425 * using the basic #sort method.
1427 * files = Dir["*"]
1428 * sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime }
1429 * sorted #=> ["mon", "tues", "wed", "thurs"]
1431 * This sort is inefficient: it generates two new File
1432 * objects during every comparison. A slightly better technique is to
1433 * use the Kernel#test method to generate the modification
1434 * times directly.
1436 * files = Dir["*"]
1437 * sorted = files.sort { |a, b|
1438 * test(?M, a) <=> test(?M, b)
1440 * sorted #=> ["mon", "tues", "wed", "thurs"]
1442 * This still generates many unnecessary Time objects. A more
1443 * efficient technique is to cache the sort keys (modification times
1444 * in this case) before the sort. Perl users often call this approach
1445 * a Schwartzian transform, after Randal Schwartz. We construct a
1446 * temporary array, where each element is an array containing our
1447 * sort key along with the filename. We sort this array, and then
1448 * extract the filename from the result.
1450 * sorted = Dir["*"].collect { |f|
1451 * [test(?M, f), f]
1452 * }.sort.collect { |f| f[1] }
1453 * sorted #=> ["mon", "tues", "wed", "thurs"]
1455 * This is exactly what #sort_by does internally.
1457 * sorted = Dir["*"].sort_by { |f| test(?M, f) }
1458 * sorted #=> ["mon", "tues", "wed", "thurs"]
1460 * To produce the reverse of a specific order, the following can be used:
1462 * ary.sort_by { ... }.reverse!
1465 static VALUE
1466 enum_sort_by(VALUE obj)
1468 VALUE ary, buf;
1469 struct MEMO *memo;
1470 long i;
1471 struct sort_by_data *data;
1473 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
1475 if (RB_TYPE_P(obj, T_ARRAY) && RARRAY_LEN(obj) <= LONG_MAX/2) {
1476 ary = rb_ary_new2(RARRAY_LEN(obj)*2);
1478 else {
1479 ary = rb_ary_new();
1481 RBASIC_CLEAR_CLASS(ary);
1482 buf = rb_ary_tmp_new(SORT_BY_BUFSIZE*2);
1483 rb_ary_store(buf, SORT_BY_BUFSIZE*2-1, Qnil);
1484 memo = MEMO_NEW(0, 0, 0);
1485 data = (struct sort_by_data *)&memo->v1;
1486 RB_OBJ_WRITE(memo, &data->ary, ary);
1487 RB_OBJ_WRITE(memo, &data->buf, buf);
1488 data->n = 0;
1489 rb_block_call(obj, id_each, 0, 0, sort_by_i, (VALUE)memo);
1490 ary = data->ary;
1491 buf = data->buf;
1492 if (data->n) {
1493 rb_ary_resize(buf, data->n*2);
1494 rb_ary_concat(ary, buf);
1496 if (RARRAY_LEN(ary) > 2) {
1497 RARRAY_PTR_USE(ary, ptr,
1498 ruby_qsort(ptr, RARRAY_LEN(ary)/2, 2*sizeof(VALUE),
1499 sort_by_cmp, (void *)ary));
1501 if (RBASIC(ary)->klass) {
1502 rb_raise(rb_eRuntimeError, "sort_by reentered");
1504 for (i=1; i<RARRAY_LEN(ary); i+=2) {
1505 RARRAY_ASET(ary, i/2, RARRAY_AREF(ary, i));
1507 rb_ary_resize(ary, RARRAY_LEN(ary)/2);
1508 RBASIC_SET_CLASS_RAW(ary, rb_cArray);
1510 return ary;
1513 #define ENUMFUNC(name) argc ? name##_eqq : rb_block_given_p() ? name##_iter_i : name##_i
1515 #define MEMO_ENUM_NEW(v1) (rb_check_arity(argc, 0, 1), MEMO_NEW((v1), (argc ? *argv : 0), 0))
1517 #define DEFINE_ENUMFUNCS(name) \
1518 static VALUE enum_##name##_func(VALUE result, struct MEMO *memo); \
1520 static VALUE \
1521 name##_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1523 return enum_##name##_func(rb_enum_values_pack(argc, argv), MEMO_CAST(memo)); \
1526 static VALUE \
1527 name##_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1529 return enum_##name##_func(rb_yield_values2(argc, argv), MEMO_CAST(memo)); \
1532 static VALUE \
1533 name##_eqq(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1535 ENUM_WANT_SVALUE(); \
1536 return enum_##name##_func(rb_funcallv(MEMO_CAST(memo)->v2, id_eqq, 1, &i), MEMO_CAST(memo)); \
1539 static VALUE \
1540 enum_##name##_func(VALUE result, struct MEMO *memo)
1542 #define WARN_UNUSED_BLOCK(argc) do { \
1543 if ((argc) > 0 && rb_block_given_p()) { \
1544 rb_warn("given block not used"); \
1546 } while (0)
1548 DEFINE_ENUMFUNCS(all)
1550 if (!RTEST(result)) {
1551 MEMO_V1_SET(memo, Qfalse);
1552 rb_iter_break();
1554 return Qnil;
1558 * call-seq:
1559 * all? -> true or false
1560 * all?(pattern) -> true or false
1561 * all? {|element| ... } -> true or false
1563 * Returns whether every element meets a given criterion.
1565 * With no argument and no block,
1566 * returns whether every element is truthy:
1568 * (1..4).all? # => true
1569 * %w[a b c d].all? # => true
1570 * [1, 2, nil].all? # => false
1571 * ['a','b', false].all? # => false
1572 * [].all? # => true
1574 * With argument +pattern+ and no block,
1575 * returns whether for each element +element+,
1576 * <tt>pattern === element</tt>:
1578 * (1..4).all?(Integer) # => true
1579 * (1..4).all?(Numeric) # => true
1580 * (1..4).all?(Float) # => false
1581 * %w[bar baz bat bam].all?(/ba/) # => true
1582 * %w[bar baz bat bam].all?(/bar/) # => false
1583 * %w[bar baz bat bam].all?('ba') # => false
1584 * {foo: 0, bar: 1, baz: 2}.all?(Array) # => true
1585 * {foo: 0, bar: 1, baz: 2}.all?(Hash) # => false
1586 * [].all?(Integer) # => true
1588 * With a block given, returns whether the block returns a truthy value
1589 * for every element:
1591 * (1..4).all? {|element| element < 5 } # => true
1592 * (1..4).all? {|element| element < 4 } # => false
1593 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 3 } # => true
1594 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 2 } # => false
1596 * Related: #any?, #none? #one?.
1600 static VALUE
1601 enum_all(int argc, VALUE *argv, VALUE obj)
1603 struct MEMO *memo = MEMO_ENUM_NEW(Qtrue);
1604 WARN_UNUSED_BLOCK(argc);
1605 rb_block_call(obj, id_each, 0, 0, ENUMFUNC(all), (VALUE)memo);
1606 return memo->v1;
1609 DEFINE_ENUMFUNCS(any)
1611 if (RTEST(result)) {
1612 MEMO_V1_SET(memo, Qtrue);
1613 rb_iter_break();
1615 return Qnil;
1619 * call-seq:
1620 * any? -> true or false
1621 * any?(pattern) -> true or false
1622 * any? {|element| ... } -> true or false
1624 * Returns whether any element meets a given criterion.
1626 * With no argument and no block,
1627 * returns whether any element is truthy:
1629 * (1..4).any? # => true
1630 * %w[a b c d].any? # => true
1631 * [1, false, nil].any? # => true
1632 * [].any? # => false
1634 * With argument +pattern+ and no block,
1635 * returns whether for any element +element+,
1636 * <tt>pattern === element</tt>:
1638 * [nil, false, 0].any?(Integer) # => true
1639 * [nil, false, 0].any?(Numeric) # => true
1640 * [nil, false, 0].any?(Float) # => false
1641 * %w[bar baz bat bam].any?(/m/) # => true
1642 * %w[bar baz bat bam].any?(/foo/) # => false
1643 * %w[bar baz bat bam].any?('ba') # => false
1644 * {foo: 0, bar: 1, baz: 2}.any?(Array) # => true
1645 * {foo: 0, bar: 1, baz: 2}.any?(Hash) # => false
1646 * [].any?(Integer) # => false
1648 * With a block given, returns whether the block returns a truthy value
1649 * for any element:
1651 * (1..4).any? {|element| element < 2 } # => true
1652 * (1..4).any? {|element| element < 1 } # => false
1653 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 1 } # => true
1654 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 0 } # => false
1657 * Related: #all?, #none?, #one?.
1660 static VALUE
1661 enum_any(int argc, VALUE *argv, VALUE obj)
1663 struct MEMO *memo = MEMO_ENUM_NEW(Qfalse);
1664 WARN_UNUSED_BLOCK(argc);
1665 rb_block_call(obj, id_each, 0, 0, ENUMFUNC(any), (VALUE)memo);
1666 return memo->v1;
1669 DEFINE_ENUMFUNCS(one)
1671 if (RTEST(result)) {
1672 if (memo->v1 == Qundef) {
1673 MEMO_V1_SET(memo, Qtrue);
1675 else if (memo->v1 == Qtrue) {
1676 MEMO_V1_SET(memo, Qfalse);
1677 rb_iter_break();
1680 return Qnil;
1683 struct nmin_data {
1684 long n;
1685 long bufmax;
1686 long curlen;
1687 VALUE buf;
1688 VALUE limit;
1689 int (*cmpfunc)(const void *, const void *, void *);
1690 int rev: 1; /* max if 1 */
1691 int by: 1; /* min_by if 1 */
1694 static VALUE
1695 cmpint_reenter_check(struct nmin_data *data, VALUE val)
1697 if (RBASIC(data->buf)->klass) {
1698 rb_raise(rb_eRuntimeError, "%s%s reentered",
1699 data->rev ? "max" : "min",
1700 data->by ? "_by" : "");
1702 return val;
1705 static int
1706 nmin_cmp(const void *ap, const void *bp, void *_data)
1708 struct cmp_opt_data cmp_opt = { 0, 0 };
1709 struct nmin_data *data = (struct nmin_data *)_data;
1710 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1711 #define rb_cmpint(cmp, a, b) rb_cmpint(cmpint_reenter_check(data, (cmp)), a, b)
1712 return OPTIMIZED_CMP(a, b, cmp_opt);
1713 #undef rb_cmpint
1716 static int
1717 nmin_block_cmp(const void *ap, const void *bp, void *_data)
1719 struct nmin_data *data = (struct nmin_data *)_data;
1720 VALUE a = *(const VALUE *)ap, b = *(const VALUE *)bp;
1721 VALUE cmp = rb_yield_values(2, a, b);
1722 cmpint_reenter_check(data, cmp);
1723 return rb_cmpint(cmp, a, b);
1726 static void
1727 nmin_filter(struct nmin_data *data)
1729 long n;
1730 VALUE *beg;
1731 int eltsize;
1732 long numelts;
1734 long left, right;
1735 long store_index;
1737 long i, j;
1739 if (data->curlen <= data->n)
1740 return;
1742 n = data->n;
1743 beg = RARRAY_PTR(data->buf);
1744 eltsize = data->by ? 2 : 1;
1745 numelts = data->curlen;
1747 left = 0;
1748 right = numelts-1;
1750 #define GETPTR(i) (beg+(i)*eltsize)
1752 #define SWAP(i, j) do { \
1753 VALUE tmp[2]; \
1754 memcpy(tmp, GETPTR(i), sizeof(VALUE)*eltsize); \
1755 memcpy(GETPTR(i), GETPTR(j), sizeof(VALUE)*eltsize); \
1756 memcpy(GETPTR(j), tmp, sizeof(VALUE)*eltsize); \
1757 } while (0)
1759 while (1) {
1760 long pivot_index = left + (right-left)/2;
1761 long num_pivots = 1;
1763 SWAP(pivot_index, right);
1764 pivot_index = right;
1766 store_index = left;
1767 i = left;
1768 while (i <= right-num_pivots) {
1769 int c = data->cmpfunc(GETPTR(i), GETPTR(pivot_index), data);
1770 if (data->rev)
1771 c = -c;
1772 if (c == 0) {
1773 SWAP(i, right-num_pivots);
1774 num_pivots++;
1775 continue;
1777 if (c < 0) {
1778 SWAP(i, store_index);
1779 store_index++;
1781 i++;
1783 j = store_index;
1784 for (i = right; right-num_pivots < i; i--) {
1785 if (i <= j)
1786 break;
1787 SWAP(j, i);
1788 j++;
1791 if (store_index <= n && n <= store_index+num_pivots)
1792 break;
1794 if (n < store_index) {
1795 right = store_index-1;
1797 else {
1798 left = store_index+num_pivots;
1801 #undef GETPTR
1802 #undef SWAP
1804 data->limit = RARRAY_AREF(data->buf, store_index*eltsize); /* the last pivot */
1805 data->curlen = data->n;
1806 rb_ary_resize(data->buf, data->n * eltsize);
1809 static VALUE
1810 nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data))
1812 struct nmin_data *data = (struct nmin_data *)_data;
1813 VALUE cmpv;
1815 ENUM_WANT_SVALUE();
1817 if (data->by)
1818 cmpv = enum_yield(argc, i);
1819 else
1820 cmpv = i;
1822 if (data->limit != Qundef) {
1823 int c = data->cmpfunc(&cmpv, &data->limit, data);
1824 if (data->rev)
1825 c = -c;
1826 if (c >= 0)
1827 return Qnil;
1830 if (data->by)
1831 rb_ary_push(data->buf, cmpv);
1832 rb_ary_push(data->buf, i);
1834 data->curlen++;
1836 if (data->curlen == data->bufmax) {
1837 nmin_filter(data);
1840 return Qnil;
1843 VALUE
1844 rb_nmin_run(VALUE obj, VALUE num, int by, int rev, int ary)
1846 VALUE result;
1847 struct nmin_data data;
1849 data.n = NUM2LONG(num);
1850 if (data.n < 0)
1851 rb_raise(rb_eArgError, "negative size (%ld)", data.n);
1852 if (data.n == 0)
1853 return rb_ary_new2(0);
1854 if (LONG_MAX/4/(by ? 2 : 1) < data.n)
1855 rb_raise(rb_eArgError, "too big size");
1856 data.bufmax = data.n * 4;
1857 data.curlen = 0;
1858 data.buf = rb_ary_tmp_new(data.bufmax * (by ? 2 : 1));
1859 data.limit = Qundef;
1860 data.cmpfunc = by ? nmin_cmp :
1861 rb_block_given_p() ? nmin_block_cmp :
1862 nmin_cmp;
1863 data.rev = rev;
1864 data.by = by;
1865 if (ary) {
1866 long i;
1867 for (i = 0; i < RARRAY_LEN(obj); i++) {
1868 VALUE args[1];
1869 args[0] = RARRAY_AREF(obj, i);
1870 nmin_i(obj, (VALUE)&data, 1, args, Qundef);
1873 else {
1874 rb_block_call(obj, id_each, 0, 0, nmin_i, (VALUE)&data);
1876 nmin_filter(&data);
1877 result = data.buf;
1878 if (by) {
1879 long i;
1880 RARRAY_PTR_USE(result, ptr, {
1881 ruby_qsort(ptr,
1882 RARRAY_LEN(result)/2,
1883 sizeof(VALUE)*2,
1884 data.cmpfunc, (void *)&data);
1885 for (i=1; i<RARRAY_LEN(result); i+=2) {
1886 ptr[i/2] = ptr[i];
1889 rb_ary_resize(result, RARRAY_LEN(result)/2);
1891 else {
1892 RARRAY_PTR_USE(result, ptr, {
1893 ruby_qsort(ptr, RARRAY_LEN(result), sizeof(VALUE),
1894 data.cmpfunc, (void *)&data);
1897 if (rev) {
1898 rb_ary_reverse(result);
1900 RBASIC_SET_CLASS(result, rb_cArray);
1901 return result;
1906 * call-seq:
1907 * one? -> true or false
1908 * one?(pattern) -> true or false
1909 * one? {|element| ... } -> true or false
1911 * Returns whether exactly one element meets a given criterion.
1913 * With no argument and no block,
1914 * returns whether exactly one element is truthy:
1916 * (1..1).one? # => true
1917 * [1, nil, false].one? # => true
1918 * (1..4).one? # => false
1919 * {foo: 0}.one? # => true
1920 * {foo: 0, bar: 1}.one? # => false
1921 * [].one? # => false
1923 * With argument +pattern+ and no block,
1924 * returns whether for exactly one element +element+,
1925 * <tt>pattern === element</tt>:
1927 * [nil, false, 0].one?(Integer) # => true
1928 * [nil, false, 0].one?(Numeric) # => true
1929 * [nil, false, 0].one?(Float) # => false
1930 * %w[bar baz bat bam].one?(/m/) # => true
1931 * %w[bar baz bat bam].one?(/foo/) # => false
1932 * %w[bar baz bat bam].one?('ba') # => false
1933 * {foo: 0, bar: 1, baz: 2}.one?(Array) # => false
1934 * {foo: 0}.one?(Array) # => true
1935 * [].one?(Integer) # => false
1937 * With a block given, returns whether the block returns a truthy value
1938 * for exactly one element:
1940 * (1..4).one? {|element| element < 2 } # => true
1941 * (1..4).one? {|element| element < 1 } # => false
1942 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true
1943 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
1945 * Related: #none?, #all?, #any?.
1948 static VALUE
1949 enum_one(int argc, VALUE *argv, VALUE obj)
1951 struct MEMO *memo = MEMO_ENUM_NEW(Qundef);
1952 VALUE result;
1954 WARN_UNUSED_BLOCK(argc);
1955 rb_block_call(obj, id_each, 0, 0, ENUMFUNC(one), (VALUE)memo);
1956 result = memo->v1;
1957 if (result == Qundef) return Qfalse;
1958 return result;
1961 DEFINE_ENUMFUNCS(none)
1963 if (RTEST(result)) {
1964 MEMO_V1_SET(memo, Qfalse);
1965 rb_iter_break();
1967 return Qnil;
1971 * call-seq:
1972 * none? -> true or false
1973 * none?(pattern) -> true or false
1974 * none? {|element| ... } -> true or false
1976 * Returns whether no element meets a given criterion.
1978 * With no argument and no block,
1979 * returns whether no element is truthy:
1981 * (1..4).none? # => false
1982 * [nil, false].none? # => true
1983 * {foo: 0}.none? # => false
1984 * {foo: 0, bar: 1}.none? # => false
1985 * [].none? # => true
1987 * With argument +pattern+ and no block,
1988 * returns whether for no element +element+,
1989 * <tt>pattern === element</tt>:
1991 * [nil, false, 1.1].none?(Integer) # => true
1992 * %w[bar baz bat bam].none?(/m/) # => false
1993 * %w[bar baz bat bam].none?(/foo/) # => true
1994 * %w[bar baz bat bam].none?('ba') # => true
1995 * {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true
1996 * {foo: 0}.none?(Array) # => false
1997 * [].none?(Integer) # => true
1999 * With a block given, returns whether the block returns a truthy value
2000 * for no element:
2002 * (1..4).none? {|element| element < 1 } # => true
2003 * (1..4).none? {|element| element < 2 } # => false
2004 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true
2005 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
2007 * Related: #one?, #all?, #any?.
2010 static VALUE
2011 enum_none(int argc, VALUE *argv, VALUE obj)
2013 struct MEMO *memo = MEMO_ENUM_NEW(Qtrue);
2015 WARN_UNUSED_BLOCK(argc);
2016 rb_block_call(obj, id_each, 0, 0, ENUMFUNC(none), (VALUE)memo);
2017 return memo->v1;
2020 struct min_t {
2021 VALUE min;
2022 struct cmp_opt_data cmp_opt;
2025 static VALUE
2026 min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2028 struct min_t *memo = MEMO_FOR(struct min_t, args);
2030 ENUM_WANT_SVALUE();
2032 if (memo->min == Qundef) {
2033 memo->min = i;
2035 else {
2036 if (OPTIMIZED_CMP(i, memo->min, memo->cmp_opt) < 0) {
2037 memo->min = i;
2040 return Qnil;
2043 static VALUE
2044 min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2046 VALUE cmp;
2047 struct min_t *memo = MEMO_FOR(struct min_t, args);
2049 ENUM_WANT_SVALUE();
2051 if (memo->min == Qundef) {
2052 memo->min = i;
2054 else {
2055 cmp = rb_yield_values(2, i, memo->min);
2056 if (rb_cmpint(cmp, i, memo->min) < 0) {
2057 memo->min = i;
2060 return Qnil;
2065 * call-seq:
2066 * min -> element
2067 * min(n) -> array
2068 * min {|a, b| ... } -> element
2069 * min(n) {|a, b| ... } -> array
2071 * Returns the element with the minimum element according to a given criterion.
2072 * The ordering of equal elements is indeterminate and may be unstable.
2074 * With no argument and no block, returns the minimum element,
2075 * using the elements' own method <tt><=></tt> for comparison:
2077 * (1..4).min # => 1
2078 * (-4..-1).min # => -4
2079 * %w[d c b a].min # => "a"
2080 * {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1]
2081 * [].min # => nil
2083 * With positive integer argument +n+ given, and no block,
2084 * returns an array containing the first +n+ minimum elements that exist:
2086 * (1..4).min(2) # => [1, 2]
2087 * (-4..-1).min(2) # => [-4, -3]
2088 * %w[d c b a].min(2) # => ["a", "b"]
2089 * {foo: 0, bar: 1, baz: 2}.min(2) # => [[:bar, 1], [:baz, 2]]
2090 * [].min(2) # => []
2092 * With a block given, the block determines the minimum elements.
2093 * The block is called with two elements +a+ and +b+, and must return:
2095 * - A negative integer if <tt>a < b</tt>.
2096 * - Zero if <tt>a == b</tt>.
2097 * - A positive integer if <tt>a > b</tt>.
2099 * With a block given and no argument,
2100 * returns the minimum element as determined by the block:
2102 * %w[xxx x xxxx xx].min {|a, b| a.size <=> b.size } # => "x"
2103 * h = {foo: 0, bar: 1, baz: 2}
2104 * h.min {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:foo, 0]
2105 * [].min {|a, b| a <=> b } # => nil
2107 * With a block given and positive integer argument +n+ given,
2108 * returns an array containing the first +n+ minimum elements that exist,
2109 * as determined by the block.
2111 * %w[xxx x xxxx xx].min(2) {|a, b| a.size <=> b.size } # => ["x", "xx"]
2112 * h = {foo: 0, bar: 1, baz: 2}
2113 * h.min(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2114 * # => [[:foo, 0], [:bar, 1]]
2115 * [].min(2) {|a, b| a <=> b } # => []
2117 * Related: #min_by, #minmax, #max.
2121 static VALUE
2122 enum_min(int argc, VALUE *argv, VALUE obj)
2124 VALUE memo;
2125 struct min_t *m = NEW_CMP_OPT_MEMO(struct min_t, memo);
2126 VALUE result;
2127 VALUE num;
2129 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2130 return rb_nmin_run(obj, num, 0, 0, 0);
2132 m->min = Qundef;
2133 m->cmp_opt.opt_methods = 0;
2134 m->cmp_opt.opt_inited = 0;
2135 if (rb_block_given_p()) {
2136 rb_block_call(obj, id_each, 0, 0, min_ii, memo);
2138 else {
2139 rb_block_call(obj, id_each, 0, 0, min_i, memo);
2141 result = m->min;
2142 if (result == Qundef) return Qnil;
2143 return result;
2146 struct max_t {
2147 VALUE max;
2148 struct cmp_opt_data cmp_opt;
2151 static VALUE
2152 max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2154 struct max_t *memo = MEMO_FOR(struct max_t, args);
2156 ENUM_WANT_SVALUE();
2158 if (memo->max == Qundef) {
2159 memo->max = i;
2161 else {
2162 if (OPTIMIZED_CMP(i, memo->max, memo->cmp_opt) > 0) {
2163 memo->max = i;
2166 return Qnil;
2169 static VALUE
2170 max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2172 struct max_t *memo = MEMO_FOR(struct max_t, args);
2173 VALUE cmp;
2175 ENUM_WANT_SVALUE();
2177 if (memo->max == Qundef) {
2178 memo->max = i;
2180 else {
2181 cmp = rb_yield_values(2, i, memo->max);
2182 if (rb_cmpint(cmp, i, memo->max) > 0) {
2183 memo->max = i;
2186 return Qnil;
2190 * call-seq:
2191 * max -> element
2192 * max(n) -> array
2193 * max {|a, b| ... } -> element
2194 * max(n) {|a, b| ... } -> array
2196 * Returns the element with the maximum element according to a given criterion.
2197 * The ordering of equal elements is indeterminate and may be unstable.
2199 * With no argument and no block, returns the maximum element,
2200 * using the elements' own method <tt><=></tt> for comparison:
2202 * (1..4).max # => 4
2203 * (-4..-1).max # => -1
2204 * %w[d c b a].max # => "d"
2205 * {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
2206 * [].max # => nil
2208 * With positive integer argument +n+ given, and no block,
2209 * returns an array containing the first +n+ maximum elements that exist:
2211 * (1..4).max(2) # => [4, 3]
2212 * (-4..-1).max(2) # => [-1, -2]
2213 * %w[d c b a].max(2) # => ["d", "c"]
2214 * {foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]]
2215 * [].max(2) # => []
2217 * With a block given, the block determines the maximum elements.
2218 * The block is called with two elements +a+ and +b+, and must return:
2220 * - A negative integer if <tt>a < b</tt>.
2221 * - Zero if <tt>a == b</tt>.
2222 * - A positive integer if <tt>a > b</tt>.
2224 * With a block given and no argument,
2225 * returns the maximum element as determined by the block:
2227 * %w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx"
2228 * h = {foo: 0, bar: 1, baz: 2}
2229 * h.max {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:baz, 2]
2230 * [].max {|a, b| a <=> b } # => nil
2232 * With a block given and positive integer argument +n+ given,
2233 * returns an array containing the first +n+ maximum elements that exist,
2234 * as determined by the block.
2236 * %w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"]
2237 * h = {foo: 0, bar: 1, baz: 2}
2238 * h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2239 * # => [[:baz, 2], [:bar, 1]]
2240 * [].max(2) {|a, b| a <=> b } # => []
2242 * Related: #min, #minmax, #max_by.
2246 static VALUE
2247 enum_max(int argc, VALUE *argv, VALUE obj)
2249 VALUE memo;
2250 struct max_t *m = NEW_CMP_OPT_MEMO(struct max_t, memo);
2251 VALUE result;
2252 VALUE num;
2254 if (rb_check_arity(argc, 0, 1) && !NIL_P(num = argv[0]))
2255 return rb_nmin_run(obj, num, 0, 1, 0);
2257 m->max = Qundef;
2258 m->cmp_opt.opt_methods = 0;
2259 m->cmp_opt.opt_inited = 0;
2260 if (rb_block_given_p()) {
2261 rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo);
2263 else {
2264 rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo);
2266 result = m->max;
2267 if (result == Qundef) return Qnil;
2268 return result;
2271 struct minmax_t {
2272 VALUE min;
2273 VALUE max;
2274 VALUE last;
2275 struct cmp_opt_data cmp_opt;
2278 static void
2279 minmax_i_update(VALUE i, VALUE j, struct minmax_t *memo)
2281 int n;
2283 if (memo->min == Qundef) {
2284 memo->min = i;
2285 memo->max = j;
2287 else {
2288 n = OPTIMIZED_CMP(i, memo->min, memo->cmp_opt);
2289 if (n < 0) {
2290 memo->min = i;
2292 n = OPTIMIZED_CMP(j, memo->max, memo->cmp_opt);
2293 if (n > 0) {
2294 memo->max = j;
2299 static VALUE
2300 minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2302 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2303 int n;
2304 VALUE j;
2306 ENUM_WANT_SVALUE();
2308 if (memo->last == Qundef) {
2309 memo->last = i;
2310 return Qnil;
2312 j = memo->last;
2313 memo->last = Qundef;
2315 n = OPTIMIZED_CMP(j, i, memo->cmp_opt);
2316 if (n == 0)
2317 i = j;
2318 else if (n < 0) {
2319 VALUE tmp;
2320 tmp = i;
2321 i = j;
2322 j = tmp;
2325 minmax_i_update(i, j, memo);
2327 return Qnil;
2330 static void
2331 minmax_ii_update(VALUE i, VALUE j, struct minmax_t *memo)
2333 int n;
2335 if (memo->min == Qundef) {
2336 memo->min = i;
2337 memo->max = j;
2339 else {
2340 n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min);
2341 if (n < 0) {
2342 memo->min = i;
2344 n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max);
2345 if (n > 0) {
2346 memo->max = j;
2351 static VALUE
2352 minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2354 struct minmax_t *memo = MEMO_FOR(struct minmax_t, _memo);
2355 int n;
2356 VALUE j;
2358 ENUM_WANT_SVALUE();
2360 if (memo->last == Qundef) {
2361 memo->last = i;
2362 return Qnil;
2364 j = memo->last;
2365 memo->last = Qundef;
2367 n = rb_cmpint(rb_yield_values(2, j, i), j, i);
2368 if (n == 0)
2369 i = j;
2370 else if (n < 0) {
2371 VALUE tmp;
2372 tmp = i;
2373 i = j;
2374 j = tmp;
2377 minmax_ii_update(i, j, memo);
2379 return Qnil;
2383 * call-seq:
2384 * minmax -> [minimum, maximum]
2385 * minmax {|a, b| ... } -> [minimum, maximum]
2387 * Returns a 2-element array containing the minimum and maximum elements
2388 * according to a given criterion.
2389 * The ordering of equal elements is indeterminate and may be unstable.
2391 * With no argument and no block, returns the minimum and maximum elements,
2392 * using the elements' own method <tt><=></tt> for comparison:
2394 * (1..4).minmax # => [1, 4]
2395 * (-4..-1).minmax # => [-4, -1]
2396 * %w[d c b a].minmax # => ["a", "d"]
2397 * {foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]]
2398 * [].minmax # => [nil, nil]
2400 * With a block given, returns the minimum and maximum elements
2401 * as determined by the block:
2403 * %w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"]
2404 * h = {foo: 0, bar: 1, baz: 2}
2405 * h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] }
2406 * # => [[:foo, 0], [:baz, 2]]
2407 * [].minmax {|a, b| a <=> b } # => [nil, nil]
2409 * Related: #min, #max, #minmax_by.
2413 static VALUE
2414 enum_minmax(VALUE obj)
2416 VALUE memo;
2417 struct minmax_t *m = NEW_CMP_OPT_MEMO(struct minmax_t, memo);
2419 m->min = Qundef;
2420 m->last = Qundef;
2421 m->cmp_opt.opt_methods = 0;
2422 m->cmp_opt.opt_inited = 0;
2423 if (rb_block_given_p()) {
2424 rb_block_call(obj, id_each, 0, 0, minmax_ii, memo);
2425 if (m->last != Qundef)
2426 minmax_ii_update(m->last, m->last, m);
2428 else {
2429 rb_block_call(obj, id_each, 0, 0, minmax_i, memo);
2430 if (m->last != Qundef)
2431 minmax_i_update(m->last, m->last, m);
2433 if (m->min != Qundef) {
2434 return rb_assoc_new(m->min, m->max);
2436 return rb_assoc_new(Qnil, Qnil);
2439 static VALUE
2440 min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2442 struct cmp_opt_data cmp_opt = { 0, 0 };
2443 struct MEMO *memo = MEMO_CAST(args);
2444 VALUE v;
2446 ENUM_WANT_SVALUE();
2448 v = enum_yield(argc, i);
2449 if (memo->v1 == Qundef) {
2450 MEMO_V1_SET(memo, v);
2451 MEMO_V2_SET(memo, i);
2453 else if (OPTIMIZED_CMP(v, memo->v1, cmp_opt) < 0) {
2454 MEMO_V1_SET(memo, v);
2455 MEMO_V2_SET(memo, i);
2457 return Qnil;
2461 * call-seq:
2462 * min_by {|element| ... } -> element
2463 * min_by(n) {|element| ... } -> array
2464 * min_by -> enumerator
2465 * min_by(n) -> enumerator
2467 * Returns the elements for which the block returns the minimum values.
2469 * With a block given and no argument,
2470 * returns the element for which the block returns the minimum value:
2472 * (1..4).min_by {|element| -element } # => 4
2473 * %w[a b c d].min_by {|element| -element.ord } # => "d"
2474 * {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2]
2475 * [].min_by {|element| -element } # => nil
2477 * With a block given and positive integer argument +n+ given,
2478 * returns an array containing the +n+ elements
2479 * for which the block returns minimum values:
2481 * (1..4).min_by(2) {|element| -element }
2482 * # => [4, 3]
2483 * %w[a b c d].min_by(2) {|element| -element.ord }
2484 * # => ["d", "c"]
2485 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2486 * # => [[:baz, 2], [:bar, 1]]
2487 * [].min_by(2) {|element| -element }
2488 * # => []
2490 * Returns an Enumerator if no block is given.
2492 * Related: #min, #minmax, #max_by.
2496 static VALUE
2497 enum_min_by(int argc, VALUE *argv, VALUE obj)
2499 struct MEMO *memo;
2500 VALUE num;
2502 rb_check_arity(argc, 0, 1);
2504 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2506 if (argc && !NIL_P(num = argv[0]))
2507 return rb_nmin_run(obj, num, 1, 0, 0);
2509 memo = MEMO_NEW(Qundef, Qnil, 0);
2510 rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
2511 return memo->v2;
2514 static VALUE
2515 max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
2517 struct cmp_opt_data cmp_opt = { 0, 0 };
2518 struct MEMO *memo = MEMO_CAST(args);
2519 VALUE v;
2521 ENUM_WANT_SVALUE();
2523 v = enum_yield(argc, i);
2524 if (memo->v1 == Qundef) {
2525 MEMO_V1_SET(memo, v);
2526 MEMO_V2_SET(memo, i);
2528 else if (OPTIMIZED_CMP(v, memo->v1, cmp_opt) > 0) {
2529 MEMO_V1_SET(memo, v);
2530 MEMO_V2_SET(memo, i);
2532 return Qnil;
2536 * call-seq:
2537 * max_by {|element| ... } -> element
2538 * max_by(n) {|element| ... } -> array
2539 * max_by -> enumerator
2540 * max_by(n) -> enumerator
2542 * Returns the elements for which the block returns the maximum values.
2544 * With a block given and no argument,
2545 * returns the element for which the block returns the maximum value:
2547 * (1..4).max_by {|element| -element } # => 1
2548 * %w[a b c d].max_by {|element| -element.ord } # => "a"
2549 * {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
2550 * [].max_by {|element| -element } # => nil
2552 * With a block given and positive integer argument +n+ given,
2553 * returns an array containing the +n+ elements
2554 * for which the block returns maximum values:
2556 * (1..4).max_by(2) {|element| -element }
2557 * # => [1, 2]
2558 * %w[a b c d].max_by(2) {|element| -element.ord }
2559 * # => ["a", "b"]
2560 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2561 * # => [[:foo, 0], [:bar, 1]]
2562 * [].max_by(2) {|element| -element }
2563 * # => []
2565 * Returns an Enumerator if no block is given.
2567 * Related: #max, #minmax, #min_by.
2571 static VALUE
2572 enum_max_by(int argc, VALUE *argv, VALUE obj)
2574 struct MEMO *memo;
2575 VALUE num;
2577 rb_check_arity(argc, 0, 1);
2579 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2581 if (argc && !NIL_P(num = argv[0]))
2582 return rb_nmin_run(obj, num, 1, 1, 0);
2584 memo = MEMO_NEW(Qundef, Qnil, 0);
2585 rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
2586 return memo->v2;
2589 struct minmax_by_t {
2590 VALUE min_bv;
2591 VALUE max_bv;
2592 VALUE min;
2593 VALUE max;
2594 VALUE last_bv;
2595 VALUE last;
2598 static void
2599 minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *memo)
2601 struct cmp_opt_data cmp_opt = { 0, 0 };
2603 if (memo->min_bv == Qundef) {
2604 memo->min_bv = v1;
2605 memo->max_bv = v2;
2606 memo->min = i1;
2607 memo->max = i2;
2609 else {
2610 if (OPTIMIZED_CMP(v1, memo->min_bv, cmp_opt) < 0) {
2611 memo->min_bv = v1;
2612 memo->min = i1;
2614 if (OPTIMIZED_CMP(v2, memo->max_bv, cmp_opt) > 0) {
2615 memo->max_bv = v2;
2616 memo->max = i2;
2621 static VALUE
2622 minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
2624 struct cmp_opt_data cmp_opt = { 0, 0 };
2625 struct minmax_by_t *memo = MEMO_FOR(struct minmax_by_t, _memo);
2626 VALUE vi, vj, j;
2627 int n;
2629 ENUM_WANT_SVALUE();
2631 vi = enum_yield(argc, i);
2633 if (memo->last_bv == Qundef) {
2634 memo->last_bv = vi;
2635 memo->last = i;
2636 return Qnil;
2638 vj = memo->last_bv;
2639 j = memo->last;
2640 memo->last_bv = Qundef;
2642 n = OPTIMIZED_CMP(vj, vi, cmp_opt);
2643 if (n == 0) {
2644 i = j;
2645 vi = vj;
2647 else if (n < 0) {
2648 VALUE tmp;
2649 tmp = i;
2650 i = j;
2651 j = tmp;
2652 tmp = vi;
2653 vi = vj;
2654 vj = tmp;
2657 minmax_by_i_update(vi, vj, i, j, memo);
2659 return Qnil;
2663 * call-seq:
2664 * minmax_by {|element| ... } -> [minimum, maximum]
2665 * minmax_by -> enumerator
2667 * Returns a 2-element array containing the elements
2668 * for which the block returns minimum and maximum values:
2670 * (1..4).minmax_by {|element| -element }
2671 * # => [4, 1]
2672 * %w[a b c d].minmax_by {|element| -element.ord }
2673 * # => ["d", "a"]
2674 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2675 * # => [[:baz, 2], [:foo, 0]]
2676 * [].minmax_by {|element| -element }
2677 * # => [nil, nil]
2679 * Returns an Enumerator if no block is given.
2681 * Related: #max_by, #minmax, #min_by.
2685 static VALUE
2686 enum_minmax_by(VALUE obj)
2688 VALUE memo;
2689 struct minmax_by_t *m = NEW_MEMO_FOR(struct minmax_by_t, memo);
2691 RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
2693 m->min_bv = Qundef;
2694 m->max_bv = Qundef;
2695 m->min = Qnil;
2696 m->max = Qnil;
2697 m->last_bv = Qundef;
2698 m->last = Qundef;
2699 rb_block_call(obj, id_each, 0, 0, minmax_by_i, memo);
2700 if (m->last_bv != Qundef)
2701 minmax_by_i_update(m->last_bv, m->last_bv, m->last, m->last, m);
2702 m = MEMO_FOR(struct minmax_by_t, memo);
2703 return rb_assoc_new(m->min, m->max);
2706 static VALUE
2707 member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
2709 struct MEMO *memo = MEMO_CAST(args);
2711 if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
2712 MEMO_V2_SET(memo, Qtrue);
2713 rb_iter_break();
2715 return Qnil;
2719 * call-seq:
2720 * include?(object) -> true or false
2722 * Returns whether for any element <tt>object == element</tt>:
2724 * (1..4).include?(2) # => true
2725 * (1..4).include?(5) # => false
2726 * (1..4).include?('2') # => false
2727 * %w[a b c d].include?('b') # => true
2728 * %w[a b c d].include?('2') # => false
2729 * {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true
2730 * {foo: 0, bar: 1, baz: 2}.include?('foo') # => false
2731 * {foo: 0, bar: 1, baz: 2}.include?(0) # => false
2733 * Enumerable#member? is an alias for Enumerable#include?.
2737 static VALUE
2738 enum_member(VALUE obj, VALUE val)
2740 struct MEMO *memo = MEMO_NEW(val, Qfalse, 0);
2742 rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
2743 return memo->v2;
2746 static VALUE
2747 each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
2749 struct MEMO *m = MEMO_CAST(memo);
2750 VALUE n = imemo_count_value(m);
2752 imemo_count_up(m);
2753 return rb_yield_values(2, rb_enum_values_pack(argc, argv), n);
2757 * call-seq:
2758 * each_with_index(*args) {|element, i| ..... } -> self
2759 * each_with_index(*args) -> enumerator
2761 * With a block given, calls the block with each element and its index;
2762 * returns +self+:
2764 * h = {}
2765 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
2766 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
2768 * h = {}
2769 * %w[a b c d].each_with_index {|element, i| h[element] = i }
2770 * # => ["a", "b", "c", "d"]
2771 * h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
2773 * a = []
2774 * h = {foo: 0, bar: 1, baz: 2}
2775 * h.each_with_index {|element, i| a.push([i, element]) }
2776 * # => {:foo=>0, :bar=>1, :baz=>2}
2777 * a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]
2779 * With no block given, returns an Enumerator.
2783 static VALUE
2784 enum_each_with_index(int argc, VALUE *argv, VALUE obj)
2786 struct MEMO *memo;
2788 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2790 memo = MEMO_NEW(0, 0, 0);
2791 rb_block_call(obj, id_each, argc, argv, each_with_index_i, (VALUE)memo);
2792 return obj;
2797 * call-seq:
2798 * reverse_each(*args) {|element| ... } -> self
2799 * reverse_each(*args) -> enumerator
2801 * With a block given, calls the block with each element,
2802 * but in reverse order; returns +self+:
2804 * a = []
2805 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
2806 * a # => [-4, -3, -2, -1]
2808 * a = []
2809 * %w[a b c d].reverse_each {|element| a.push(element) }
2810 * # => ["a", "b", "c", "d"]
2811 * a # => ["d", "c", "b", "a"]
2813 * a = []
2814 * h.reverse_each {|element| a.push(element) }
2815 * # => {:foo=>0, :bar=>1, :baz=>2}
2816 * a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
2818 * With no block given, returns an Enumerator.
2822 static VALUE
2823 enum_reverse_each(int argc, VALUE *argv, VALUE obj)
2825 VALUE ary;
2826 long len;
2828 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2830 ary = enum_to_a(argc, argv, obj);
2832 len = RARRAY_LEN(ary);
2833 while (len--) {
2834 long nlen;
2835 rb_yield(RARRAY_AREF(ary, len));
2836 nlen = RARRAY_LEN(ary);
2837 if (nlen < len) {
2838 len = nlen;
2842 return obj;
2846 static VALUE
2847 each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
2849 ENUM_WANT_SVALUE();
2850 enum_yield(argc, i);
2851 return Qnil;
2855 * call-seq:
2856 * each_entry(*args) {|element| ... } -> self
2857 * each_entry(*args) -> enumerator
2859 * Calls the given block with each element,
2860 * converting multiple values from yield to an array; returns +self+:
2862 * a = []
2863 * (1..4).each_entry {|element| a.push(element) } # => 1..4
2864 * a # => [1, 2, 3, 4]
2866 * a = []
2867 * h = {foo: 0, bar: 1, baz:2}
2868 * h.each_entry {|element| a.push(element) }
2869 * # => {:foo=>0, :bar=>1, :baz=>2}
2870 * a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
2872 * class Foo
2873 * include Enumerable
2874 * def each
2875 * yield 1
2876 * yield 1, 2
2877 * yield
2878 * end
2879 * end
2880 * Foo.new.each_entry {|yielded| p yielded }
2882 * Output:
2885 * [1, 2]
2886 * nil
2888 * With no block given, returns an Enumerator.
2892 static VALUE
2893 enum_each_entry(int argc, VALUE *argv, VALUE obj)
2895 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
2896 rb_block_call(obj, id_each, argc, argv, each_val_i, 0);
2897 return obj;
2900 static VALUE
2901 add_int(VALUE x, long n)
2903 const VALUE y = LONG2NUM(n);
2904 if (RB_INTEGER_TYPE_P(x)) return rb_int_plus(x, y);
2905 return rb_funcallv(x, '+', 1, &y);
2908 static VALUE
2909 div_int(VALUE x, long n)
2911 const VALUE y = LONG2NUM(n);
2912 if (RB_INTEGER_TYPE_P(x)) return rb_int_idiv(x, y);
2913 return rb_funcallv(x, id_div, 1, &y);
2916 #define dont_recycle_block_arg(arity) ((arity) == 1 || (arity) < 0)
2918 static VALUE
2919 each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m))
2921 struct MEMO *memo = MEMO_CAST(m);
2922 VALUE ary = memo->v1;
2923 VALUE v = Qnil;
2924 long size = memo->u3.cnt;
2925 ENUM_WANT_SVALUE();
2927 rb_ary_push(ary, i);
2929 if (RARRAY_LEN(ary) == size) {
2930 v = rb_yield(ary);
2932 if (memo->v2) {
2933 MEMO_V1_SET(memo, rb_ary_new2(size));
2935 else {
2936 rb_ary_clear(ary);
2940 return v;
2943 static VALUE
2944 enum_each_slice_size(VALUE obj, VALUE args, VALUE eobj)
2946 VALUE n, size;
2947 long slice_size = NUM2LONG(RARRAY_AREF(args, 0));
2948 ID infinite_p;
2949 CONST_ID(infinite_p, "infinite?");
2950 if (slice_size <= 0) rb_raise(rb_eArgError, "invalid slice size");
2952 size = enum_size(obj, 0, 0);
2953 if (NIL_P(size)) return Qnil;
2954 if (RB_FLOAT_TYPE_P(size) && RTEST(rb_funcall(size, infinite_p, 0))) {
2955 return size;
2958 n = add_int(size, slice_size-1);
2959 return div_int(n, slice_size);
2963 * call-seq:
2964 * each_slice(n) { ... } -> self
2965 * each_slice(n) -> enumerator
2967 * Calls the block with each successive disjoint +n+-tuple of elements;
2968 * returns +self+:
2970 * a = []
2971 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
2972 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
2974 * a = []
2975 * h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4}
2976 * h.each_slice(2) {|tuple| a.push(tuple) }
2977 * a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
2979 * With no block given, returns an Enumerator.
2982 static VALUE
2983 enum_each_slice(VALUE obj, VALUE n)
2985 long size = NUM2LONG(n);
2986 VALUE ary;
2987 struct MEMO *memo;
2988 int arity;
2990 if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
2991 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
2992 size = limit_by_enum_size(obj, size);
2993 ary = rb_ary_new2(size);
2994 arity = rb_block_arity();
2995 memo = MEMO_NEW(ary, dont_recycle_block_arg(arity), size);
2996 rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
2997 ary = memo->v1;
2998 if (RARRAY_LEN(ary) > 0) rb_yield(ary);
3000 return obj;
3003 static VALUE
3004 each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3006 struct MEMO *memo = MEMO_CAST(args);
3007 VALUE ary = memo->v1;
3008 VALUE v = Qnil;
3009 long size = memo->u3.cnt;
3010 ENUM_WANT_SVALUE();
3012 if (RARRAY_LEN(ary) == size) {
3013 rb_ary_shift(ary);
3015 rb_ary_push(ary, i);
3016 if (RARRAY_LEN(ary) == size) {
3017 if (memo->v2) {
3018 ary = rb_ary_dup(ary);
3020 v = rb_yield(ary);
3022 return v;
3025 static VALUE
3026 enum_each_cons_size(VALUE obj, VALUE args, VALUE eobj)
3028 struct cmp_opt_data cmp_opt = { 0, 0 };
3029 const VALUE zero = LONG2FIX(0);
3030 VALUE n, size;
3031 long cons_size = NUM2LONG(RARRAY_AREF(args, 0));
3032 if (cons_size <= 0) rb_raise(rb_eArgError, "invalid size");
3034 size = enum_size(obj, 0, 0);
3035 if (NIL_P(size)) return Qnil;
3037 n = add_int(size, 1 - cons_size);
3038 return (OPTIMIZED_CMP(n, zero, cmp_opt) == -1) ? zero : n;
3042 * call-seq:
3043 * each_cons(n) { ... } -> self
3044 * each_cons(n) -> enumerator
3046 * Calls the block with each successive overlapped +n+-tuple of elements;
3047 * returns +self+:
3049 * a = []
3050 * (1..5).each_cons(3) {|element| a.push(element) }
3051 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3053 * a = []
3054 * h = {foo: 0, bar: 1, baz: 2, bam: 3}
3055 * h.each_cons(2) {|element| a.push(element) }
3056 * a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
3058 * With no block given, returns an Enumerator.
3061 static VALUE
3062 enum_each_cons(VALUE obj, VALUE n)
3064 long size = NUM2LONG(n);
3065 struct MEMO *memo;
3066 int arity;
3068 if (size <= 0) rb_raise(rb_eArgError, "invalid size");
3069 RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
3070 arity = rb_block_arity();
3071 if (enum_size_over_p(obj, size)) return obj;
3072 memo = MEMO_NEW(rb_ary_new2(size), dont_recycle_block_arg(arity), size);
3073 rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
3075 return obj;
3078 static VALUE
3079 each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
3081 ENUM_WANT_SVALUE();
3082 return rb_yield_values(2, i, memo);
3086 * call-seq:
3087 * each_with_object(object) { |(*args), memo_object| ... } -> object
3088 * each_with_object(object) -> enumerator
3090 * Calls the block once for each element, passing both the element
3091 * and the given object:
3093 * (1..4).each_with_object([]) {|i, a| a.push(i**2) } # => [1, 4, 9, 16]
3094 * h.each_with_object({}) {|element, h| k, v = *element; h[v] = k }
3095 * # => {0=>:foo, 1=>:bar, 2=>:baz}
3097 * With no block given, returns an Enumerator.
3100 static VALUE
3101 enum_each_with_object(VALUE obj, VALUE memo)
3103 RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
3105 rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
3107 return memo;
3110 static VALUE
3111 zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3113 struct MEMO *memo = (struct MEMO *)memoval;
3114 VALUE result = memo->v1;
3115 VALUE args = memo->v2;
3116 long n = memo->u3.cnt++;
3117 VALUE tmp;
3118 int i;
3120 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3121 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3122 for (i=0; i<RARRAY_LEN(args); i++) {
3123 VALUE e = RARRAY_AREF(args, i);
3125 if (RARRAY_LEN(e) <= n) {
3126 rb_ary_push(tmp, Qnil);
3128 else {
3129 rb_ary_push(tmp, RARRAY_AREF(e, n));
3132 if (NIL_P(result)) {
3133 enum_yield_array(tmp);
3135 else {
3136 rb_ary_push(result, tmp);
3139 RB_GC_GUARD(args);
3141 return Qnil;
3144 static VALUE
3145 call_next(VALUE w)
3147 VALUE *v = (VALUE *)w;
3148 return v[0] = rb_funcallv(v[1], id_next, 0, 0);
3151 static VALUE
3152 call_stop(VALUE w, VALUE _)
3154 VALUE *v = (VALUE *)w;
3155 return v[0] = Qundef;
3158 static VALUE
3159 zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
3161 struct MEMO *memo = (struct MEMO *)memoval;
3162 VALUE result = memo->v1;
3163 VALUE args = memo->v2;
3164 VALUE tmp;
3165 int i;
3167 tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
3168 rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
3169 for (i=0; i<RARRAY_LEN(args); i++) {
3170 if (NIL_P(RARRAY_AREF(args, i))) {
3171 rb_ary_push(tmp, Qnil);
3173 else {
3174 VALUE v[2];
3176 v[1] = RARRAY_AREF(args, i);
3177 rb_rescue2(call_next, (VALUE)v, call_stop, (VALUE)v, rb_eStopIteration, (VALUE)0);
3178 if (v[0] == Qundef) {
3179 RARRAY_ASET(args, i, Qnil);
3180 v[0] = Qnil;
3182 rb_ary_push(tmp, v[0]);
3185 if (NIL_P(result)) {
3186 enum_yield_array(tmp);
3188 else {
3189 rb_ary_push(result, tmp);
3192 RB_GC_GUARD(args);
3194 return Qnil;
3198 * call-seq:
3199 * zip(*other_enums) -> array
3200 * zip(*other_enums) {|array| ... } -> nil
3202 * With no block given, returns a new array +new_array+ of size self.size
3203 * whose elements are arrays.
3204 * Each nested array <tt>new_array[n]</tt>
3205 * is of size <tt>other_enums.size+1</tt>, and contains:
3207 * - The +n+-th element of self.
3208 * - The +n+-th element of each of the +other_enums+.
3210 * If all +other_enums+ and self are the same size,
3211 * all elements are included in the result, and there is no +nil+-filling:
3213 * a = [:a0, :a1, :a2, :a3]
3214 * b = [:b0, :b1, :b2, :b3]
3215 * c = [:c0, :c1, :c2, :c3]
3216 * d = a.zip(b, c)
3217 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3219 * f = {foo: 0, bar: 1, baz: 2}
3220 * g = {goo: 3, gar: 4, gaz: 5}
3221 * h = {hoo: 6, har: 7, haz: 8}
3222 * d = f.zip(g, h)
3223 * d # => [
3224 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3225 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3226 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
3227 * # ]
3229 * If any enumerable in other_enums is smaller than self,
3230 * fills to <tt>self.size</tt> with +nil+:
3232 * a = [:a0, :a1, :a2, :a3]
3233 * b = [:b0, :b1, :b2]
3234 * c = [:c0, :c1]
3235 * d = a.zip(b, c)
3236 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
3238 * If any enumerable in other_enums is larger than self,
3239 * its trailing elements are ignored:
3241 * a = [:a0, :a1, :a2, :a3]
3242 * b = [:b0, :b1, :b2, :b3, :b4]
3243 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
3244 * d = a.zip(b, c)
3245 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3247 * When a block is given, calls the block with each of the sub-arrays
3248 * (formed as above); returns nil:
3250 * a = [:a0, :a1, :a2, :a3]
3251 * b = [:b0, :b1, :b2, :b3]
3252 * c = [:c0, :c1, :c2, :c3]
3253 * a.zip(b, c) {|sub_array| p sub_array} # => nil
3255 * Output:
3257 * [:a0, :b0, :c0]
3258 * [:a1, :b1, :c1]
3259 * [:a2, :b2, :c2]
3260 * [:a3, :b3, :c3]
3264 static VALUE
3265 enum_zip(int argc, VALUE *argv, VALUE obj)
3267 int i;
3268 ID conv;
3269 struct MEMO *memo;
3270 VALUE result = Qnil;
3271 VALUE args = rb_ary_new4(argc, argv);
3272 int allary = TRUE;
3274 argv = RARRAY_PTR(args);
3275 for (i=0; i<argc; i++) {
3276 VALUE ary = rb_check_array_type(argv[i]);
3277 if (NIL_P(ary)) {
3278 allary = FALSE;
3279 break;
3281 argv[i] = ary;
3283 if (!allary) {
3284 static const VALUE sym_each = STATIC_ID2SYM(id_each);
3285 CONST_ID(conv, "to_enum");
3286 for (i=0; i<argc; i++) {
3287 if (!rb_respond_to(argv[i], id_each)) {
3288 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (must respond to :each)",
3289 rb_obj_class(argv[i]));
3291 argv[i] = rb_funcallv(argv[i], conv, 1, &sym_each);
3294 if (!rb_block_given_p()) {
3295 result = rb_ary_new();
3298 /* TODO: use NODE_DOT2 as memo(v, v, -) */
3299 memo = MEMO_NEW(result, args, 0);
3300 rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
3302 return result;
3305 static VALUE
3306 take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3308 struct MEMO *memo = MEMO_CAST(args);
3309 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3310 if (--memo->u3.cnt == 0) rb_iter_break();
3311 return Qnil;
3315 * call-seq:
3316 * take(n) -> array
3318 * For non-negative integer +n+, returns the first +n+ elements:
3320 * r = (1..4)
3321 * r.take(2) # => [1, 2]
3322 * r.take(0) # => []
3324 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3325 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3329 static VALUE
3330 enum_take(VALUE obj, VALUE n)
3332 struct MEMO *memo;
3333 VALUE result;
3334 long len = NUM2LONG(n);
3336 if (len < 0) {
3337 rb_raise(rb_eArgError, "attempt to take negative size");
3340 if (len == 0) return rb_ary_new2(0);
3341 result = rb_ary_new2(len);
3342 memo = MEMO_NEW(result, 0, len);
3343 rb_block_call(obj, id_each, 0, 0, take_i, (VALUE)memo);
3344 return result;
3348 static VALUE
3349 take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3351 if (!RTEST(rb_yield_values2(argc, argv))) rb_iter_break();
3352 rb_ary_push(ary, rb_enum_values_pack(argc, argv));
3353 return Qnil;
3357 * call-seq:
3358 * take_while {|element| ... } -> array
3359 * take_while -> enumerator
3361 * Calls the block with successive elements as long as the block
3362 * returns a truthy value;
3363 * returns an array of all elements up to that point:
3366 * (1..4).take_while{|i| i < 3 } # => [1, 2]
3367 * h = {foo: 0, bar: 1, baz: 2}
3368 * h.take_while{|element| key, value = *element; value < 2 }
3369 * # => [[:foo, 0], [:bar, 1]]
3371 * With no block given, returns an Enumerator.
3375 static VALUE
3376 enum_take_while(VALUE obj)
3378 VALUE ary;
3380 RETURN_ENUMERATOR(obj, 0, 0);
3381 ary = rb_ary_new();
3382 rb_block_call(obj, id_each, 0, 0, take_while_i, ary);
3383 return ary;
3386 static VALUE
3387 drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3389 struct MEMO *memo = MEMO_CAST(args);
3390 if (memo->u3.cnt == 0) {
3391 rb_ary_push(memo->v1, rb_enum_values_pack(argc, argv));
3393 else {
3394 memo->u3.cnt--;
3396 return Qnil;
3400 * call-seq:
3401 * drop(n) -> array
3403 * For positive integer +n+, returns an array containing
3404 * all but the first +n+ elements:
3406 * r = (1..4)
3407 * r.drop(3) # => [4]
3408 * r.drop(2) # => [3, 4]
3409 * r.drop(1) # => [2, 3, 4]
3410 * r.drop(0) # => [1, 2, 3, 4]
3411 * r.drop(50) # => []
3413 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3414 * h.drop(2) # => [[:baz, 2], [:bat, 3]]
3418 static VALUE
3419 enum_drop(VALUE obj, VALUE n)
3421 VALUE result;
3422 struct MEMO *memo;
3423 long len = NUM2LONG(n);
3425 if (len < 0) {
3426 rb_raise(rb_eArgError, "attempt to drop negative size");
3429 result = rb_ary_new();
3430 memo = MEMO_NEW(result, 0, len);
3431 rb_block_call(obj, id_each, 0, 0, drop_i, (VALUE)memo);
3432 return result;
3436 static VALUE
3437 drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
3439 struct MEMO *memo = MEMO_CAST(args);
3440 ENUM_WANT_SVALUE();
3442 if (!memo->u3.state && !RTEST(enum_yield(argc, i))) {
3443 memo->u3.state = TRUE;
3445 if (memo->u3.state) {
3446 rb_ary_push(memo->v1, i);
3448 return Qnil;
3452 * call-seq:
3453 * drop_while {|element| ... } -> array
3454 * drop_while -> enumerator
3456 * Calls the block with successive elements as long as the block
3457 * returns a truthy value;
3458 * returns an array of all elements after that point:
3461 * (1..4).drop_while{|i| i < 3 } # => [3, 4]
3462 * h = {foo: 0, bar: 1, baz: 2}
3463 * a = h.drop_while{|element| key, value = *element; value < 2 }
3464 * a # => [[:baz, 2]]
3466 * With no block given, returns an Enumerator.
3470 static VALUE
3471 enum_drop_while(VALUE obj)
3473 VALUE result;
3474 struct MEMO *memo;
3476 RETURN_ENUMERATOR(obj, 0, 0);
3477 result = rb_ary_new();
3478 memo = MEMO_NEW(result, 0, FALSE);
3479 rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
3480 return result;
3483 static VALUE
3484 cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3486 ENUM_WANT_SVALUE();
3488 rb_ary_push(ary, argc > 1 ? i : rb_ary_new_from_values(argc, argv));
3489 enum_yield(argc, i);
3490 return Qnil;
3493 static VALUE
3494 enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
3496 long mul = 0;
3497 VALUE n = Qnil;
3498 VALUE size;
3500 if (args && (RARRAY_LEN(args) > 0)) {
3501 n = RARRAY_AREF(args, 0);
3502 if (!NIL_P(n)) mul = NUM2LONG(n);
3505 size = enum_size(self, args, 0);
3506 if (NIL_P(size) || FIXNUM_ZERO_P(size)) return size;
3508 if (NIL_P(n)) return DBL2NUM(HUGE_VAL);
3509 if (mul <= 0) return INT2FIX(0);
3510 n = LONG2FIX(mul);
3511 return rb_funcallv(size, '*', 1, &n);
3515 * call-seq:
3516 * cycle(n = nil) {|element| ...} -> nil
3517 * cycle(n = nil) -> enumerator
3519 * When called with positive integer argument +n+ and a block,
3520 * calls the block with each element, then does so again,
3521 * until it has done so +n+ times; returns +nil+:
3523 * a = []
3524 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3525 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3526 * a = []
3527 * ('a'..'d').cycle(2) {|element| a.push(element) }
3528 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3529 * a = []
3530 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3531 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3533 * If count is zero or negative, does not call the block.
3535 * When called with a block and +n+ is +nil+, cycles forever.
3537 * When no block is given, returns an Enumerator.
3541 static VALUE
3542 enum_cycle(int argc, VALUE *argv, VALUE obj)
3544 VALUE ary;
3545 VALUE nv = Qnil;
3546 long n, i, len;
3548 rb_check_arity(argc, 0, 1);
3550 RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
3551 if (!argc || NIL_P(nv = argv[0])) {
3552 n = -1;
3554 else {
3555 n = NUM2LONG(nv);
3556 if (n <= 0) return Qnil;
3558 ary = rb_ary_new();
3559 RBASIC_CLEAR_CLASS(ary);
3560 rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
3561 len = RARRAY_LEN(ary);
3562 if (len == 0) return Qnil;
3563 while (n < 0 || 0 < --n) {
3564 for (i=0; i<len; i++) {
3565 enum_yield_array(RARRAY_AREF(ary, i));
3568 return Qnil;
3571 struct chunk_arg {
3572 VALUE categorize;
3573 VALUE prev_value;
3574 VALUE prev_elts;
3575 VALUE yielder;
3578 static VALUE
3579 chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3581 struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
3582 VALUE v, s;
3583 VALUE alone = ID2SYM(id__alone);
3584 VALUE separator = ID2SYM(id__separator);
3586 ENUM_WANT_SVALUE();
3588 v = rb_funcallv(argp->categorize, id_call, 1, &i);
3590 if (v == alone) {
3591 if (!NIL_P(argp->prev_value)) {
3592 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3593 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3594 argp->prev_value = argp->prev_elts = Qnil;
3596 v = rb_assoc_new(v, rb_ary_new3(1, i));
3597 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3599 else if (NIL_P(v) || v == separator) {
3600 if (!NIL_P(argp->prev_value)) {
3601 v = rb_assoc_new(argp->prev_value, argp->prev_elts);
3602 rb_funcallv(argp->yielder, id_lshift, 1, &v);
3603 argp->prev_value = argp->prev_elts = Qnil;
3606 else if (SYMBOL_P(v) && (s = rb_sym2str(v), RSTRING_PTR(s)[0] == '_')) {
3607 rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
3609 else {
3610 if (NIL_P(argp->prev_value)) {
3611 argp->prev_value = v;
3612 argp->prev_elts = rb_ary_new3(1, i);
3614 else {
3615 if (rb_equal(argp->prev_value, v)) {
3616 rb_ary_push(argp->prev_elts, i);
3618 else {
3619 s = rb_assoc_new(argp->prev_value, argp->prev_elts);
3620 rb_funcallv(argp->yielder, id_lshift, 1, &s);
3621 argp->prev_value = v;
3622 argp->prev_elts = rb_ary_new3(1, i);
3626 return Qnil;
3629 static VALUE
3630 chunk_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
3632 VALUE enumerable;
3633 VALUE arg;
3634 struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
3636 enumerable = rb_ivar_get(enumerator, id_chunk_enumerable);
3637 memo->categorize = rb_ivar_get(enumerator, id_chunk_categorize);
3638 memo->prev_value = Qnil;
3639 memo->prev_elts = Qnil;
3640 memo->yielder = yielder;
3642 rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
3643 memo = MEMO_FOR(struct chunk_arg, arg);
3644 if (!NIL_P(memo->prev_elts)) {
3645 arg = rb_assoc_new(memo->prev_value, memo->prev_elts);
3646 rb_funcallv(memo->yielder, id_lshift, 1, &arg);
3648 return Qnil;
3652 * call-seq:
3653 * chunk {|array| ... } -> enumerator
3655 * Each element in the returned enumerator is a 2-element array consisting of:
3657 * - A value returned by the block.
3658 * - An array ("chunk") containing the element for which that value was returned,
3659 * and all following elements for which the block returned the same value:
3661 * So that:
3663 * - Each block return value that is different from its predecessor
3664 * begins a new chunk.
3665 * - Each block return value that is the same as its predecessor
3666 * continues the same chunk.
3668 * Example:
3670 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3671 * # The enumerator elements.
3672 * e.next # => [0, [0, 1, 2]]
3673 * e.next # => [1, [3, 4, 5]]
3674 * e.next # => [2, [6, 7, 8]]
3675 * e.next # => [3, [9, 10]]
3677 * \Method +chunk+ is especially useful for an enumerable that is already sorted.
3678 * This example counts words for each initial letter in a large array of words:
3680 * # Get sorted words from a web page.
3681 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3682 * words = URI::open(url).readlines
3683 * # Make chunks, one for each letter.
3684 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3685 * # Display 'A' through 'F'.
3686 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3688 * Output:
3690 * ["A", 17096]
3691 * ["B", 11070]
3692 * ["C", 19901]
3693 * ["D", 10896]
3694 * ["E", 8736]
3695 * ["F", 6860]
3697 * You can use the special symbol <tt>:_alone</tt> to force an element
3698 * into its own separate chuck:
3700 * a = [0, 0, 1, 1]
3701 * e = a.chunk{|i| i.even? ? :_alone : true }
3702 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3704 * For example, you can put each line that contains a URL into its own chunk:
3706 * pattern = /http/
3707 * open(filename) { |f|
3708 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3709 * pp lines
3713 * You can use the special symbol <tt>:_separator</tt> or +nil+
3714 * to force an element to be ignored (not included in any chunk):
3716 * a = [0, 0, -1, 1, 1]
3717 * e = a.chunk{|i| i < 0 ? :_separator : true }
3718 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3720 * Note that the separator does end the chunk:
3722 * a = [0, 0, -1, 1, -1, 1]
3723 * e = a.chunk{|i| i < 0 ? :_separator : true }
3724 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3726 * For example, the sequence of hyphens in svn log can be eliminated as follows:
3728 * sep = "-"*72 + "\n"
3729 * IO.popen("svn log README") { |f|
3730 * f.chunk { |line|
3731 * line != sep || nil
3732 * }.each { |_, lines|
3733 * pp lines
3736 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
3737 * # "\n",
3738 * # "* README, README.ja: Update the portability section.\n",
3739 * # "\n"]
3740 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
3741 * # "\n",
3742 * # "* README, README.ja: Add a note about default C flags.\n",
3743 * # "\n"]
3744 * # ...
3746 * Paragraphs separated by empty lines can be parsed as follows:
3748 * File.foreach("README").chunk { |line|
3749 * /\A\s*\z/ !~ line || nil
3750 * }.each { |_, lines|
3751 * pp lines
3755 static VALUE
3756 enum_chunk(VALUE enumerable)
3758 VALUE enumerator;
3760 RETURN_SIZED_ENUMERATOR(enumerable, 0, 0, enum_size);
3762 enumerator = rb_obj_alloc(rb_cEnumerator);
3763 rb_ivar_set(enumerator, id_chunk_enumerable, enumerable);
3764 rb_ivar_set(enumerator, id_chunk_categorize, rb_block_proc());
3765 rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
3766 return enumerator;
3770 struct slicebefore_arg {
3771 VALUE sep_pred;
3772 VALUE sep_pat;
3773 VALUE prev_elts;
3774 VALUE yielder;
3777 static VALUE
3778 slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
3780 struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
3781 VALUE header_p;
3783 ENUM_WANT_SVALUE();
3785 if (!NIL_P(argp->sep_pat))
3786 header_p = rb_funcallv(argp->sep_pat, id_eqq, 1, &i);
3787 else
3788 header_p = rb_funcallv(argp->sep_pred, id_call, 1, &i);
3789 if (RTEST(header_p)) {
3790 if (!NIL_P(argp->prev_elts))
3791 rb_funcallv(argp->yielder, id_lshift, 1, &argp->prev_elts);
3792 argp->prev_elts = rb_ary_new3(1, i);
3794 else {
3795 if (NIL_P(argp->prev_elts))
3796 argp->prev_elts = rb_ary_new3(1, i);
3797 else
3798 rb_ary_push(argp->prev_elts, i);
3801 return Qnil;
3804 static VALUE
3805 slicebefore_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
3807 VALUE enumerable;
3808 VALUE arg;
3809 struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
3811 enumerable = rb_ivar_get(enumerator, id_slicebefore_enumerable);
3812 memo->sep_pred = rb_attr_get(enumerator, id_slicebefore_sep_pred);
3813 memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, id_slicebefore_sep_pat) : Qnil;
3814 memo->prev_elts = Qnil;
3815 memo->yielder = yielder;
3817 rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
3818 memo = MEMO_FOR(struct slicebefore_arg, arg);
3819 if (!NIL_P(memo->prev_elts))
3820 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
3821 return Qnil;
3825 * call-seq:
3826 * slice_before(pattern) -> enumerator
3827 * slice_before {|array| ... } -> enumerator
3829 * With argument +pattern+, returns an enumerator that uses the pattern
3830 * to partition elements into arrays ("slices").
3831 * An element begins a new slice if <tt>element === pattern</tt>
3832 * (or if it is the first element).
3834 * a = %w[foo bar fop for baz fob fog bam foy]
3835 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
3836 * e.each {|array| p array }
3838 * Output:
3840 * ["foo"]
3841 * ["bar", "fop", "for"]
3842 * ["baz", "fob", "fog"]
3843 * ["bam", "foy"]
3845 * With a block, returns an enumerator that uses the block
3846 * to partition elements into arrays.
3847 * An element begins a new slice if its block return is a truthy value
3848 * (or if it is the first element):
3850 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
3851 * e.each {|array| p array }
3853 * Output:
3855 * [1]
3856 * [2, 3, 4, 5]
3857 * [6, 7, 8, 9]
3858 * [10, 11, 12, 13]
3859 * [14, 15, 16, 17]
3860 * [18, 19, 20]
3862 * Other methods of the Enumerator class and Enumerable module,
3863 * such as +to_a+, +map+, etc., are also usable.
3865 * For example, iteration over ChangeLog entries can be implemented as
3866 * follows:
3868 * # iterate over ChangeLog entries.
3869 * open("ChangeLog") { |f|
3870 * f.slice_before(/\A\S/).each { |e| pp e }
3873 * # same as above. block is used instead of pattern argument.
3874 * open("ChangeLog") { |f|
3875 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
3878 * "svn proplist -R" produces multiline output for each file.
3879 * They can be chunked as follows:
3881 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
3882 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
3884 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
3885 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
3886 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
3887 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
3888 * # ...
3890 * If the block needs to maintain state over multiple elements,
3891 * local variables can be used.
3892 * For example, three or more consecutive increasing numbers can be squashed
3893 * as follows (see +chunk_while+ for a better way):
3895 * a = [0, 2, 3, 4, 6, 7, 9]
3896 * prev = a[0]
3897 * p a.slice_before { |e|
3898 * prev, prev2 = e, prev
3899 * prev2 + 1 != e
3900 * }.map { |es|
3901 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
3902 * }.join(",")
3903 * #=> "0,2-4,6,7,9"
3905 * However local variables should be used carefully
3906 * if the result enumerator is enumerated twice or more.
3907 * The local variables should be initialized for each enumeration.
3908 * Enumerator.new can be used to do it.
3910 * # Word wrapping. This assumes all characters have same width.
3911 * def wordwrap(words, maxwidth)
3912 * Enumerator.new {|y|
3913 * # cols is initialized in Enumerator.new.
3914 * cols = 0
3915 * words.slice_before { |w|
3916 * cols += 1 if cols != 0
3917 * cols += w.length
3918 * if maxwidth < cols
3919 * cols = w.length
3920 * true
3921 * else
3922 * false
3923 * end
3924 * }.each {|ws| y.yield ws }
3926 * end
3927 * text = (1..20).to_a.join(" ")
3928 * enum = wordwrap(text.split(/\s+/), 10)
3929 * puts "-"*10
3930 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
3931 * puts "-"*10
3932 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
3933 * puts "-"*10
3934 * #=> ----------
3935 * # 1 2 3 4 5
3936 * # 6 7 8 9 10
3937 * # 11 12 13
3938 * # 14 15 16
3939 * # 17 18 19
3940 * # 20
3941 * # ----------
3942 * # 1 2 3 4 5
3943 * # 6 7 8 9 10
3944 * # 11 12 13
3945 * # 14 15 16
3946 * # 17 18 19
3947 * # 20
3948 * # ----------
3950 * mbox contains series of mails which start with Unix From line.
3951 * So each mail can be extracted by slice before Unix From line.
3953 * # parse mbox
3954 * open("mbox") { |f|
3955 * f.slice_before { |line|
3956 * line.start_with? "From "
3957 * }.each { |mail|
3958 * unix_from = mail.shift
3959 * i = mail.index("\n")
3960 * header = mail[0...i]
3961 * body = mail[(i+1)..-1]
3962 * body.pop if body.last == "\n"
3963 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
3964 * p unix_from
3965 * pp fields
3966 * pp body
3970 * # split mails in mbox (slice before Unix From line after an empty line)
3971 * open("mbox") { |f|
3972 * emp = true
3973 * f.slice_before { |line|
3974 * prevemp = emp
3975 * emp = line == "\n"
3976 * prevemp && line.start_with?("From ")
3977 * }.each { |mail|
3978 * mail.pop if mail.last == "\n"
3979 * pp mail
3984 static VALUE
3985 enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
3987 VALUE enumerator;
3989 if (rb_block_given_p()) {
3990 if (argc != 0)
3991 rb_error_arity(argc, 0, 0);
3992 enumerator = rb_obj_alloc(rb_cEnumerator);
3993 rb_ivar_set(enumerator, id_slicebefore_sep_pred, rb_block_proc());
3995 else {
3996 VALUE sep_pat;
3997 rb_scan_args(argc, argv, "1", &sep_pat);
3998 enumerator = rb_obj_alloc(rb_cEnumerator);
3999 rb_ivar_set(enumerator, id_slicebefore_sep_pat, sep_pat);
4001 rb_ivar_set(enumerator, id_slicebefore_enumerable, enumerable);
4002 rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
4003 return enumerator;
4007 struct sliceafter_arg {
4008 VALUE pat;
4009 VALUE pred;
4010 VALUE prev_elts;
4011 VALUE yielder;
4014 static VALUE
4015 sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4017 #define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4018 struct sliceafter_arg *memo;
4019 int split_p;
4020 UPDATE_MEMO;
4022 ENUM_WANT_SVALUE();
4024 if (NIL_P(memo->prev_elts)) {
4025 memo->prev_elts = rb_ary_new3(1, i);
4027 else {
4028 rb_ary_push(memo->prev_elts, i);
4031 if (NIL_P(memo->pred)) {
4032 split_p = RTEST(rb_funcallv(memo->pat, id_eqq, 1, &i));
4033 UPDATE_MEMO;
4035 else {
4036 split_p = RTEST(rb_funcallv(memo->pred, id_call, 1, &i));
4037 UPDATE_MEMO;
4040 if (split_p) {
4041 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4042 UPDATE_MEMO;
4043 memo->prev_elts = Qnil;
4046 return Qnil;
4047 #undef UPDATE_MEMO
4050 static VALUE
4051 sliceafter_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
4053 VALUE enumerable;
4054 VALUE arg;
4055 struct sliceafter_arg *memo = NEW_MEMO_FOR(struct sliceafter_arg, arg);
4057 enumerable = rb_ivar_get(enumerator, id_sliceafter_enum);
4058 memo->pat = rb_ivar_get(enumerator, id_sliceafter_pat);
4059 memo->pred = rb_attr_get(enumerator, id_sliceafter_pred);
4060 memo->prev_elts = Qnil;
4061 memo->yielder = yielder;
4063 rb_block_call(enumerable, id_each, 0, 0, sliceafter_ii, arg);
4064 memo = MEMO_FOR(struct sliceafter_arg, arg);
4065 if (!NIL_P(memo->prev_elts))
4066 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4067 return Qnil;
4071 * call-seq:
4072 * slice_after(pattern) -> enumerator
4073 * slice_after {|array| ... } -> enumerator
4075 * With argument +pattern+, returns an enumerator that uses the pattern
4076 * to partition elements into arrays ("slices").
4077 * An element ends the current slice if <tt>element === pattern</tt>:
4079 * a = %w[foo bar fop for baz fob fog bam foy]
4080 * e = a.slice_after(/ba/) # => #<Enumerator: ...>
4081 * e.each {|array| p array }
4083 * Output:
4085 * ["foo", "bar"]
4086 * ["fop", "for", "baz"]
4087 * ["fob", "fog", "bam"]
4088 * ["foy"]
4090 * With a block, returns an enumerator that uses the block
4091 * to partition elements into arrays.
4092 * An element ends the current slice if its block return is a truthy value:
4094 * e = (1..20).slice_after {|i| i % 4 == 2 } # => #<Enumerator: ...>
4095 * e.each {|array| p array }
4097 * Output:
4099 * [1, 2]
4100 * [3, 4, 5, 6]
4101 * [7, 8, 9, 10]
4102 * [11, 12, 13, 14]
4103 * [15, 16, 17, 18]
4104 * [19, 20]
4106 * Other methods of the Enumerator class and Enumerable module,
4107 * such as +map+, etc., are also usable.
4109 * For example, continuation lines (lines end with backslash) can be
4110 * concatenated as follows:
4112 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4113 * e = lines.slice_after(/(?<!\\)\n\z/)
4114 * p e.to_a
4115 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4116 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4117 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4121 static VALUE
4122 enum_slice_after(int argc, VALUE *argv, VALUE enumerable)
4124 VALUE enumerator;
4125 VALUE pat = Qnil, pred = Qnil;
4127 if (rb_block_given_p()) {
4128 if (0 < argc)
4129 rb_raise(rb_eArgError, "both pattern and block are given");
4130 pred = rb_block_proc();
4132 else {
4133 rb_scan_args(argc, argv, "1", &pat);
4136 enumerator = rb_obj_alloc(rb_cEnumerator);
4137 rb_ivar_set(enumerator, id_sliceafter_enum, enumerable);
4138 rb_ivar_set(enumerator, id_sliceafter_pat, pat);
4139 rb_ivar_set(enumerator, id_sliceafter_pred, pred);
4141 rb_block_call(enumerator, idInitialize, 0, 0, sliceafter_i, enumerator);
4142 return enumerator;
4145 struct slicewhen_arg {
4146 VALUE pred;
4147 VALUE prev_elt;
4148 VALUE prev_elts;
4149 VALUE yielder;
4150 int inverted; /* 0 for slice_when and 1 for chunk_while. */
4153 static VALUE
4154 slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
4156 #define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4157 struct slicewhen_arg *memo;
4158 int split_p;
4159 UPDATE_MEMO;
4161 ENUM_WANT_SVALUE();
4163 if (memo->prev_elt == Qundef) {
4164 /* The first element */
4165 memo->prev_elt = i;
4166 memo->prev_elts = rb_ary_new3(1, i);
4168 else {
4169 VALUE args[2];
4170 args[0] = memo->prev_elt;
4171 args[1] = i;
4172 split_p = RTEST(rb_funcallv(memo->pred, id_call, 2, args));
4173 UPDATE_MEMO;
4175 if (memo->inverted)
4176 split_p = !split_p;
4178 if (split_p) {
4179 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4180 UPDATE_MEMO;
4181 memo->prev_elts = rb_ary_new3(1, i);
4183 else {
4184 rb_ary_push(memo->prev_elts, i);
4187 memo->prev_elt = i;
4190 return Qnil;
4191 #undef UPDATE_MEMO
4194 static VALUE
4195 slicewhen_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
4197 VALUE enumerable;
4198 VALUE arg;
4199 struct slicewhen_arg *memo =
4200 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg, arg, inverted);
4202 enumerable = rb_ivar_get(enumerator, id_slicewhen_enum);
4203 memo->pred = rb_attr_get(enumerator, id_slicewhen_pred);
4204 memo->prev_elt = Qundef;
4205 memo->prev_elts = Qnil;
4206 memo->yielder = yielder;
4207 memo->inverted = RTEST(rb_attr_get(enumerator, id_slicewhen_inverted));
4209 rb_block_call(enumerable, id_each, 0, 0, slicewhen_ii, arg);
4210 memo = MEMO_FOR(struct slicewhen_arg, arg);
4211 if (!NIL_P(memo->prev_elts))
4212 rb_funcallv(memo->yielder, id_lshift, 1, &memo->prev_elts);
4213 return Qnil;
4217 * call-seq:
4218 * slice_when {|element, next_element| ... } -> enumerator
4220 * The returned enumerator uses the block
4221 * to partition elements into arrays ("slices");
4222 * it calls the block with each element and its successor;
4223 * begins a new slice if and only if the block returns a truthy value:
4225 * a = [0, 1, 2, 4, 5, 6, 8, 9]
4226 * e = a.slice_when {|i, j| j != i + 1 }
4227 * e.each {|array| p array }
4229 * Output:
4231 * [0, 1, 2]
4232 * [4, 5, 6]
4233 * [8, 9]
4236 static VALUE
4237 enum_slice_when(VALUE enumerable)
4239 VALUE enumerator;
4240 VALUE pred;
4242 pred = rb_block_proc();
4244 enumerator = rb_obj_alloc(rb_cEnumerator);
4245 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4246 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4247 rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
4249 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4250 return enumerator;
4254 * call-seq:
4255 * chunk_while {|element, next_element| ... } -> enumerator
4257 * The returned Enumerator uses the block to partition elements
4258 * into arrays ("chunks");
4259 * it calls the block with each element and its successor;
4260 * begins a new chunk if and only if the block returns a truthy value:
4262 * Example:
4264 * a = [1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21]
4265 * e = a.chunk_while {|i, j| j == i + 1 }
4266 * e.each {|array| p array }
4268 * Output:
4270 * [1, 2]
4271 * [4]
4272 * [9, 10, 11, 12]
4273 * [15, 16]
4274 * [19, 20, 21]
4277 static VALUE
4278 enum_chunk_while(VALUE enumerable)
4280 VALUE enumerator;
4281 VALUE pred;
4283 pred = rb_block_proc();
4285 enumerator = rb_obj_alloc(rb_cEnumerator);
4286 rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
4287 rb_ivar_set(enumerator, id_slicewhen_pred, pred);
4288 rb_ivar_set(enumerator, id_slicewhen_inverted, Qtrue);
4290 rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
4291 return enumerator;
4294 struct enum_sum_memo {
4295 VALUE v, r;
4296 long n;
4297 double f, c;
4298 int block_given;
4299 int float_value;
4302 static void
4303 sum_iter_normalize_memo(struct enum_sum_memo *memo)
4305 assert(FIXABLE(memo->n));
4306 memo->v = rb_fix_plus(LONG2FIX(memo->n), memo->v);
4307 memo->n = 0;
4309 switch (TYPE(memo->r)) {
4310 case T_RATIONAL: memo->v = rb_rational_plus(memo->r, memo->v); break;
4311 case T_UNDEF: break;
4312 default: UNREACHABLE; /* or ...? */
4314 memo->r = Qundef;
4317 static void
4318 sum_iter_fixnum(VALUE i, struct enum_sum_memo *memo)
4320 memo->n += FIX2LONG(i); /* should not overflow long type */
4321 if (! FIXABLE(memo->n)) {
4322 memo->v = rb_big_plus(LONG2NUM(memo->n), memo->v);
4323 memo->n = 0;
4327 static void
4328 sum_iter_bignum(VALUE i, struct enum_sum_memo *memo)
4330 memo->v = rb_big_plus(i, memo->v);
4333 static void
4334 sum_iter_rational(VALUE i, struct enum_sum_memo *memo)
4336 if (memo->r == Qundef) {
4337 memo->r = i;
4339 else {
4340 memo->r = rb_rational_plus(memo->r, i);
4344 static void
4345 sum_iter_some_value(VALUE i, struct enum_sum_memo *memo)
4347 memo->v = rb_funcallv(memo->v, idPLUS, 1, &i);
4350 static void
4351 sum_iter_Kahan_Babuska(VALUE i, struct enum_sum_memo *memo)
4354 * Kahan-Babuska balancing compensated summation algorithm
4355 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4357 double x;
4359 switch (TYPE(i)) {
4360 case T_FLOAT: x = RFLOAT_VALUE(i); break;
4361 case T_FIXNUM: x = FIX2LONG(i); break;
4362 case T_BIGNUM: x = rb_big2dbl(i); break;
4363 case T_RATIONAL: x = rb_num2dbl(i); break;
4364 default:
4365 memo->v = DBL2NUM(memo->f);
4366 memo->float_value = 0;
4367 sum_iter_some_value(i, memo);
4368 return;
4371 double f = memo->f;
4373 if (isnan(f)) {
4374 return;
4376 else if (! isfinite(x)) {
4377 if (isinf(x) && isinf(f) && signbit(x) != signbit(f)) {
4378 i = DBL2NUM(f);
4379 x = nan("");
4381 memo->v = i;
4382 memo->f = x;
4383 return;
4385 else if (isinf(f)) {
4386 return;
4389 double c = memo->c;
4390 double t = f + x;
4392 if (fabs(f) >= fabs(x)) {
4393 c += ((f - t) + x);
4395 else {
4396 c += ((x - t) + f);
4398 f = t;
4400 memo->f = f;
4401 memo->c = c;
4404 static void
4405 sum_iter(VALUE i, struct enum_sum_memo *memo)
4407 assert(memo != NULL);
4408 if (memo->block_given) {
4409 i = rb_yield(i);
4412 if (memo->float_value) {
4413 sum_iter_Kahan_Babuska(i, memo);
4415 else switch (TYPE(memo->v)) {
4416 default: sum_iter_some_value(i, memo); return;
4417 case T_FLOAT: sum_iter_Kahan_Babuska(i, memo); return;
4418 case T_FIXNUM:
4419 case T_BIGNUM:
4420 case T_RATIONAL:
4421 switch (TYPE(i)) {
4422 case T_FIXNUM: sum_iter_fixnum(i, memo); return;
4423 case T_BIGNUM: sum_iter_bignum(i, memo); return;
4424 case T_RATIONAL: sum_iter_rational(i, memo); return;
4425 case T_FLOAT:
4426 sum_iter_normalize_memo(memo);
4427 memo->f = NUM2DBL(memo->v);
4428 memo->c = 0.0;
4429 memo->float_value = 1;
4430 sum_iter_Kahan_Babuska(i, memo);
4431 return;
4432 default:
4433 sum_iter_normalize_memo(memo);
4434 sum_iter_some_value(i, memo);
4435 return;
4440 static VALUE
4441 enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
4443 ENUM_WANT_SVALUE();
4444 sum_iter(i, (struct enum_sum_memo *) args);
4445 return Qnil;
4448 static int
4449 hash_sum_i(VALUE key, VALUE value, VALUE arg)
4451 sum_iter(rb_assoc_new(key, value), (struct enum_sum_memo *) arg);
4452 return ST_CONTINUE;
4455 static void
4456 hash_sum(VALUE hash, struct enum_sum_memo *memo)
4458 assert(RB_TYPE_P(hash, T_HASH));
4459 assert(memo != NULL);
4461 rb_hash_foreach(hash, hash_sum_i, (VALUE)memo);
4464 static VALUE
4465 int_range_sum(VALUE beg, VALUE end, int excl, VALUE init)
4467 if (excl) {
4468 if (FIXNUM_P(end))
4469 end = LONG2FIX(FIX2LONG(end) - 1);
4470 else
4471 end = rb_big_minus(end, LONG2FIX(1));
4474 if (rb_int_ge(end, beg)) {
4475 VALUE a;
4476 a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
4477 a = rb_int_mul(a, rb_int_plus(end, beg));
4478 a = rb_int_idiv(a, LONG2FIX(2));
4479 return rb_int_plus(init, a);
4482 return init;
4486 * call-seq:
4487 * sum(initial_value = 0) -> number
4488 * sum(initial_value = 0) {|element| ... } -> object
4490 * With no block given,
4491 * returns the sum of +initial_value+ and the elements:
4493 * (1..100).sum # => 5050
4494 * (1..100).sum(1) # => 5051
4495 * ('a'..'d').sum('foo') # => "fooabcd"
4497 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4498 * for performance optimizations, those methods may not be used,
4499 * and so any redefinition of those methods may not have effect here.
4501 * One such optimization: When possible, computes using Gauss's summation
4502 * formula <em>n(n+1)/2</em>:
4504 * 100 * (100 + 1) / 2 # => 5050
4506 * With a block given, calls the block with each element;
4507 * returns the sum of +initial_value+ and the block return values:
4509 * (1..4).sum {|i| i*i } # => 30
4510 * (1..4).sum(100) {|i| i*i } # => 130
4511 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4512 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4513 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4516 static VALUE
4517 enum_sum(int argc, VALUE* argv, VALUE obj)
4519 struct enum_sum_memo memo;
4520 VALUE beg, end;
4521 int excl;
4523 memo.v = (rb_check_arity(argc, 0, 1) == 0) ? LONG2FIX(0) : argv[0];
4524 memo.block_given = rb_block_given_p();
4525 memo.n = 0;
4526 memo.r = Qundef;
4528 if ((memo.float_value = RB_FLOAT_TYPE_P(memo.v))) {
4529 memo.f = RFLOAT_VALUE(memo.v);
4530 memo.c = 0.0;
4532 else {
4533 memo.f = 0.0;
4534 memo.c = 0.0;
4537 if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
4538 if (!memo.block_given && !memo.float_value &&
4539 (FIXNUM_P(beg) || RB_BIGNUM_TYPE_P(beg)) &&
4540 (FIXNUM_P(end) || RB_BIGNUM_TYPE_P(end))) {
4541 return int_range_sum(beg, end, excl, memo.v);
4545 if (RB_TYPE_P(obj, T_HASH) &&
4546 rb_method_basic_definition_p(CLASS_OF(obj), id_each))
4547 hash_sum(obj, &memo);
4548 else
4549 rb_block_call(obj, id_each, 0, 0, enum_sum_i, (VALUE)&memo);
4551 if (memo.float_value) {
4552 return DBL2NUM(memo.f + memo.c);
4554 else {
4555 if (memo.n != 0)
4556 memo.v = rb_fix_plus(LONG2FIX(memo.n), memo.v);
4557 if (memo.r != Qundef) {
4558 memo.v = rb_rational_plus(memo.r, memo.v);
4560 return memo.v;
4564 static VALUE
4565 uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4567 ENUM_WANT_SVALUE();
4568 rb_hash_add_new_element(hash, i, i);
4569 return Qnil;
4572 static VALUE
4573 uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
4575 ENUM_WANT_SVALUE();
4576 rb_hash_add_new_element(hash, rb_yield_values2(argc, argv), i);
4577 return Qnil;
4581 * call-seq:
4582 * uniq -> array
4583 * uniq {|element| ... } -> array
4585 * With no block, returns a new array containing only unique elements;
4586 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4588 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4589 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4591 * With a block, returns a new array containing only for which the block
4592 * returns a unique value:
4594 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4595 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4596 * a = %w[a b c d e e d c b a a b c d e]
4597 a.uniq {|c| c < 'c' } # => ["a", "c"]
4601 static VALUE
4602 enum_uniq(VALUE obj)
4604 VALUE hash, ret;
4605 rb_block_call_func *const func =
4606 rb_block_given_p() ? uniq_iter : uniq_func;
4608 hash = rb_obj_hide(rb_hash_new());
4609 rb_block_call(obj, id_each, 0, 0, func, hash);
4610 ret = rb_hash_values(hash);
4611 rb_hash_clear(hash);
4612 return ret;
4615 static VALUE
4616 compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
4618 ENUM_WANT_SVALUE();
4620 if (!NIL_P(i)) {
4621 rb_ary_push(ary, i);
4623 return Qnil;
4627 * call-seq:
4628 * compact -> array
4630 * Returns an array of all non-+nil+ elements:
4632 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4633 * a.compact # => [0, "a", false, false, "a", 0]
4637 static VALUE
4638 enum_compact(VALUE obj)
4640 VALUE ary;
4642 ary = rb_ary_new();
4643 rb_block_call(obj, id_each, 0, 0, compact_i, ary);
4645 return ary;
4650 * == What's Here
4652 * \Module \Enumerable provides methods that are useful to a collection class for:
4653 * - {Querying}[#module-Enumerable-label-Methods+for+Querying]
4654 * - {Fetching}[#module-Enumerable-label-Methods+for+Fetching]
4655 * - {Searching}[#module-Enumerable-label-Methods+for+Searching]
4656 * - {Sorting}[#module-Enumerable-label-Methods+for+Sorting]
4657 * - {Iterating}[#module-Enumerable-label-Methods+for+Iterating]
4658 * - {And more....}[#module-Enumerable-label-Other+Methods]
4660 * === Methods for Querying
4662 * These methods return information about the \Enumerable other than the elements themselves:
4664 * #include?, #member?:: Returns +true+ if self == object, +false+ otherwise.
4665 * #all?:: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
4666 * #any?:: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
4667 * #none?:: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
4668 * #one?:: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
4669 * #count:: Returns the count of elements,
4670 * based on an argument or block criterion, if given.
4671 * #tally:: Returns a new \Hash containing the counts of occurrences of each element.
4673 * === Methods for Fetching
4675 * These methods return entries from the \Enumerable, without modifying it:
4677 * <i>Leading, trailing, or all elements</i>:
4678 * #entries, #to_a:: Returns all elements.
4679 * #first:: Returns the first element or leading elements.
4680 * #take:: Returns a specified number of leading elements.
4681 * #drop:: Returns a specified number of trailing elements.
4682 * #take_while:: Returns leading elements as specified by the given block.
4683 * #drop_while:: Returns trailing elements as specified by the given block.
4685 * <i>Minimum and maximum value elements</i>:
4686 * #min:: Returns the elements whose values are smallest among the elements,
4687 * as determined by <tt><=></tt> or a given block.
4688 * #max:: Returns the elements whose values are largest among the elements,
4689 * as determined by <tt><=></tt> or a given block.
4690 * #minmax:: Returns a 2-element \Array containing the smallest and largest elements.
4691 * #min_by:: Returns the smallest element, as determined by the given block.
4692 * #max_by:: Returns the largest element, as determined by the given block.
4693 * #minmax_by:: Returns the smallest and largest elements, as determined by the given block.
4695 * <i>Groups, slices, and partitions</i>:
4696 * #group_by:: Returns a \Hash that partitions the elements into groups.
4697 * #partition:: Returns elements partitioned into two new Arrays, as determined by the given block.
4698 * #slice_after:: Returns a new \Enumerator whose entries are a partition of +self+,
4699 based either on a given +object+ or a given block.
4700 * #slice_before:: Returns a new \Enumerator whose entries are a partition of +self+,
4701 based either on a given +object+ or a given block.
4702 * #slice_when:: Returns a new \Enumerator whose entries are a partition of +self+
4703 based on the given block.
4704 * #chunk:: Returns elements organized into chunks as specified by the given block.
4705 * #chunk_while:: Returns elements organized into chunks as specified by the given block.
4707 * === Methods for Searching and Filtering
4709 * These methods return elements that meet a specified criterion.
4711 * #find, #detect:: Returns an element selected by the block.
4712 * #find_all, #filter, #select:: Returns elements selected by the block.
4713 * #find_index:: Returns the index of an element selected by a given object or block.
4714 * #reject:: Returns elements not rejected by the block.
4715 * #uniq:: Returns elements that are not duplicates.
4717 * === Methods for Sorting
4719 * These methods return elements in sorted order.
4721 * #sort:: Returns the elements, sorted by <tt><=></tt> or the given block.
4722 * #sort_by:: Returns the elements, sorted by the given block.
4724 * === Methods for Iterating
4726 * #each_entry:: Calls the block with each successive element
4727 * (slightly different from #each).
4728 * #each_with_index:: Calls the block with each successive element and its index.
4729 * #each_with_object:: Calls the block with each successive element and a given object.
4730 * #each_slice:: Calls the block with successive non-overlapping slices.
4731 * #each_cons:: Calls the block with successive overlapping slices.
4732 * (different from #each_slice).
4733 * #reverse_each:: Calls the block with each successive element, in reverse order.
4735 * === Other Methods
4737 * #map, #collect:: Returns objects returned by the block.
4738 * #filter_map:: Returns truthy objects returned by the block.
4739 * #flat_map, #collect_concat:: Returns flattened objects returned by the block.
4740 * #grep:: Returns elements selected by a given object
4741 * or objects returned by a given block.
4742 * #grep_v:: Returns elements selected by a given object
4743 * or objects returned by a given block.
4744 * #reduce, #inject:: Returns the object formed by combining all elements.
4745 * #sum:: Returns the sum of the elements, using method +++.
4746 * #zip:: Combines each element with elements from other enumerables;
4747 * returns the n-tuples or calls the block with each.
4748 * #cycle:: Calls the block with each element, cycling repeatedly.
4750 * == Usage
4752 * To use module \Enumerable in a collection class:
4754 * - Include it:
4756 * include Enumerable
4758 * - Implement method <tt>#each</tt>
4759 * which must yield successive elements of the collection.
4760 * The method will be called by almost any \Enumerable method.
4762 * Example:
4764 * class Foo
4765 * include Enumerable
4766 * def each
4767 * yield 1
4768 * yield 1, 2
4769 * yield
4770 * end
4771 * end
4772 * Foo.new.each_entry{ |element| p element }
4774 * Output:
4777 * [1, 2]
4778 * nil
4780 * == \Enumerable in Ruby Core Classes
4781 * Some Ruby classes include \Enumerable:
4782 * - Array
4783 * - Dir
4784 * - Hash
4785 * - IO
4786 * - Range
4787 * - Set
4788 * - Struct
4789 * Virtually all methods in \Enumerable call method +#each+ in the including class:
4790 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element \Array.
4791 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element \Array.
4792 * - For the other classes above, +#each+ yields the next object from the collection.
4794 * == About the Examples
4795 * The example code snippets for the \Enumerable methods:
4796 * - Always show the use of one or more \Array-like classes (often \Array itself).
4797 * - Sometimes show the use of a \Hash-like class.
4798 * For some methods, though, the usage would not make sense,
4799 * and so it is not shown. Example: #tally would find exactly one of each \Hash entry.
4802 void
4803 Init_Enumerable(void)
4805 rb_mEnumerable = rb_define_module("Enumerable");
4807 rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
4808 rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
4809 rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
4811 rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
4812 rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
4813 rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
4814 rb_define_method(rb_mEnumerable, "grep_v", enum_grep_v, 1);
4815 rb_define_method(rb_mEnumerable, "count", enum_count, -1);
4816 rb_define_method(rb_mEnumerable, "find", enum_find, -1);
4817 rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
4818 rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
4819 rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
4820 rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
4821 rb_define_method(rb_mEnumerable, "filter", enum_find_all, 0);
4822 rb_define_method(rb_mEnumerable, "filter_map", enum_filter_map, 0);
4823 rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
4824 rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
4825 rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
4826 rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
4827 rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
4828 rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
4829 rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
4830 rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
4831 rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
4832 rb_define_method(rb_mEnumerable, "tally", enum_tally, -1);
4833 rb_define_method(rb_mEnumerable, "first", enum_first, -1);
4834 rb_define_method(rb_mEnumerable, "all?", enum_all, -1);
4835 rb_define_method(rb_mEnumerable, "any?", enum_any, -1);
4836 rb_define_method(rb_mEnumerable, "one?", enum_one, -1);
4837 rb_define_method(rb_mEnumerable, "none?", enum_none, -1);
4838 rb_define_method(rb_mEnumerable, "min", enum_min, -1);
4839 rb_define_method(rb_mEnumerable, "max", enum_max, -1);
4840 rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
4841 rb_define_method(rb_mEnumerable, "min_by", enum_min_by, -1);
4842 rb_define_method(rb_mEnumerable, "max_by", enum_max_by, -1);
4843 rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
4844 rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
4845 rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
4846 rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
4847 rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
4848 rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
4849 rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
4850 rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
4851 rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
4852 rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
4853 rb_define_method(rb_mEnumerable, "take", enum_take, 1);
4854 rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
4855 rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
4856 rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
4857 rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
4858 rb_define_method(rb_mEnumerable, "chunk", enum_chunk, 0);
4859 rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
4860 rb_define_method(rb_mEnumerable, "slice_after", enum_slice_after, -1);
4861 rb_define_method(rb_mEnumerable, "slice_when", enum_slice_when, 0);
4862 rb_define_method(rb_mEnumerable, "chunk_while", enum_chunk_while, 0);
4863 rb_define_method(rb_mEnumerable, "sum", enum_sum, -1);
4864 rb_define_method(rb_mEnumerable, "uniq", enum_uniq, 0);
4865 rb_define_method(rb_mEnumerable, "compact", enum_compact, 0);
4867 id__alone = rb_intern_const("_alone");
4868 id__separator = rb_intern_const("_separator");
4869 id_chunk_categorize = rb_intern_const("chunk_categorize");
4870 id_chunk_enumerable = rb_intern_const("chunk_enumerable");
4871 id_next = rb_intern_const("next");
4872 id_sliceafter_enum = rb_intern_const("sliceafter_enum");
4873 id_sliceafter_pat = rb_intern_const("sliceafter_pat");
4874 id_sliceafter_pred = rb_intern_const("sliceafter_pred");
4875 id_slicebefore_enumerable = rb_intern_const("slicebefore_enumerable");
4876 id_slicebefore_sep_pat = rb_intern_const("slicebefore_sep_pat");
4877 id_slicebefore_sep_pred = rb_intern_const("slicebefore_sep_pred");
4878 id_slicewhen_enum = rb_intern_const("slicewhen_enum");
4879 id_slicewhen_inverted = rb_intern_const("slicewhen_inverted");
4880 id_slicewhen_pred = rb_intern_const("slicewhen_pred");