1 /**********************************************************************
6 created at: Fri Oct 1 15:15:19 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
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"
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
;
45 #define id_each idEach
48 #define id_lshift idLTLT
49 #define id_call idCall
50 #define id_size idSize
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); \
65 enum_yield(int argc
, VALUE ary
)
68 return rb_yield_force_blockarg(ary
);
71 return rb_yield_values2(0, 0);
75 enum_yield_array(VALUE ary
)
77 long len
= RARRAY_LEN(ary
);
80 return rb_yield_force_blockarg(ary
);
82 return rb_yield(RARRAY_AREF(ary
, 0));
83 return rb_yield_values2(0, 0);
87 grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
89 struct MEMO
*memo
= MEMO_CAST(args
);
92 if (RTEST(rb_funcallv(memo
->v1
, id_eqq
, 1, &i
)) == RTEST(memo
->u3
.value
)) {
93 rb_ary_push(memo
->v2
, i
);
99 grep_regexp_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
101 struct MEMO
*memo
= MEMO_CAST(args
);
102 VALUE converted_element
, match
;
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
);
115 grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
117 struct MEMO
*memo
= MEMO_CAST(args
);
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
));
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()) {
135 else if (RB_TYPE_P(pat
, T_REGEXP
) &&
136 LIKELY(rb_method_basic_definition_p(CLASS_OF(pat
), idEqq
))) {
142 rb_block_call(obj
, id_each
, 0, 0, fn
, (VALUE
)memo
);
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"]
173 enum_grep(VALUE obj
, VALUE pat
)
175 return enum_grep0(obj
, pat
, Qtrue
);
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"]
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))
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) {
221 unsigned long buf
[2] = {0, 1};
222 MEMO_V3_SET(memo
, rb_big_unpack(buf
, 2));
223 memo
->flags
|= COUNT_BIGNUM
;
228 imemo_count_value(struct MEMO
*memo
)
230 if (memo
->flags
& COUNT_BIGNUM
) {
231 return memo
->u3
.value
;
234 return ULONG2NUM(memo
->u3
.cnt
);
239 count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memop
))
241 struct MEMO
*memo
= MEMO_CAST(memop
);
245 if (rb_equal(i
, memo
->v1
)) {
246 imemo_count_up(memo
);
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
);
263 count_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memop
))
265 struct MEMO
*memo
= MEMO_CAST(memop
);
267 imemo_count_up(memo
);
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
298 enum_count(int argc
, VALUE
*argv
, VALUE obj
)
302 rb_block_call_func
*func
;
305 if (rb_block_given_p()) {
313 rb_scan_args(argc
, argv
, "1", &item
);
314 if (rb_block_given_p()) {
315 rb_warn("given block not used");
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
);
326 find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memop
))
330 if (RTEST(enum_yield(argc
, i
))) {
331 struct MEMO
*memo
= MEMO_CAST(memop
);
332 MEMO_V1_SET(memo
, i
);
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.
361 enum_find(int argc
, VALUE
*argv
, VALUE obj
)
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
);
373 if (!NIL_P(if_none
)) {
374 return rb_funcallv(if_none
, id_call
, 0, 0);
380 find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memop
))
382 struct MEMO
*memo
= MEMO_CAST(memop
);
386 if (rb_equal(i
, memo
->v2
)) {
387 MEMO_V1_SET(memo
, imemo_count_value(memo
));
390 imemo_count_up(memo
);
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
));
403 imemo_count_up(memo
);
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.
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
;
439 RETURN_ENUMERATOR(obj
, 0, 0);
440 func
= find_index_iter_i
;
443 rb_scan_args(argc
, argv
, "1", &condition_value
);
444 if (rb_block_given_p()) {
445 rb_warn("given block not used");
450 memo
= MEMO_NEW(Qnil
, condition_value
, 0);
451 rb_block_call(obj
, id_each
, 0, 0, func
, (VALUE
)memo
);
456 find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
460 if (RTEST(enum_yield(argc
, i
))) {
467 enum_size(VALUE self
, VALUE args
, VALUE eobj
)
469 return rb_check_funcall_default(self
, id_size
, 0, 0, Qnil
);
473 limit_by_enum_size(VALUE obj
, long n
)
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
;
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
));
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.
509 enum_find_all(VALUE obj
)
513 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
516 rb_block_call(obj
, id_each
, 0, 0, find_all_i
, ary
);
522 filter_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
524 i
= rb_yield_values2(argc
, argv
);
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.
550 enum_filter_map(VALUE obj
)
554 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
557 rb_block_call(obj
, id_each
, 0, 0, filter_map_i
, ary
);
564 reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
568 if (!RTEST(enum_yield(argc
, i
))) {
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.
593 enum_reject(VALUE obj
)
597 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
600 rb_block_call(obj
, id_each
, 0, 0, reject_i
, ary
);
606 collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
608 rb_ary_push(ary
, rb_yield_values2(argc
, argv
));
614 collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
616 rb_ary_push(ary
, rb_enum_values_pack(argc
, argv
));
623 * map {|element| ... } -> array
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.
638 enum_collect(VALUE obj
)
641 int min_argc
, max_argc
;
643 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
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
);
653 flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
657 i
= rb_yield_values2(argc
, argv
);
658 tmp
= rb_check_array_type(i
);
664 rb_ary_concat(ary
, tmp
);
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.
689 enum_flat_map(VALUE obj
)
693 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
696 rb_block_call(obj
, id_each
, 0, 0, flat_map_i
, ary
);
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.
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
);
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
);
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());
735 enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
738 return rb_hash_set_pair(hash
, i
);
742 enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
744 return rb_hash_set_pair(hash
, rb_yield_values2(argc
, argv
));
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.
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
);
776 inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
778 struct MEMO
*memo
= MEMO_CAST(p
);
782 if (memo
->v1
== Qundef
) {
783 MEMO_V1_SET(memo
, i
);
786 MEMO_V1_SET(memo
, rb_yield_values(2, memo
->v1
, i
));
792 inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
794 struct MEMO
*memo
= MEMO_CAST(p
);
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
));
810 MEMO_V1_SET(memo
, rb_f_send(numberof(args
), args
, memo
->v1
));
816 ary_inject_op(VALUE ary
, VALUE init
, VALUE op
)
822 if (RARRAY_LEN(ary
) == 0)
823 return init
== Qundef
? Qnil
: init
;
825 if (init
== Qundef
) {
826 v
= RARRAY_AREF(ary
, 0);
828 if (RARRAY_LEN(ary
) == 1)
838 if (RB_INTEGER_TYPE_P(v
) &&
839 rb_method_basic_definition_p(rb_cInteger
, idPLUS
) &&
840 rb_obj_respond_to(v
, idPLUS
, FALSE
)) {
842 for (; i
< RARRAY_LEN(ary
); i
++) {
843 e
= RARRAY_AREF(ary
, i
);
845 n
+= FIX2LONG(e
); /* should not overflow long type */
847 v
= rb_big_plus(LONG2NUM(n
), v
);
851 else if (RB_BIGNUM_TYPE_P(e
))
852 v
= rb_big_plus(e
, v
);
857 v
= rb_fix_plus(LONG2FIX(n
), v
);
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
);
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
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:
913 * (1..4).inject(:+) # => 10
915 * [1.0, 2, 3, 4].inject(:+) # => 10.0
917 * ('a'..'d').inject(:+) # => "abcd"
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:
933 * (1..4).inject(2, :+) # => 12
935 * (1..4).inject(2.0, :+) # => 12.0
937 * ('a'..'d').inject('foo', :+) # => "fooabcd"
939 * %w[a b c].inject(['x'], :push) # => ["x", "a", "b", "c"]
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.
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"
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.
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}"
999 * "Memo: 1; element: 2"
1000 * "Memo: 3; element: 3"
1001 * "Memo: 6; element: 4"
1003 * Enumerable#reduce is an alias for Enumerable#inject.
1007 enum_inject(int argc
, VALUE
*argv
, VALUE obj
)
1011 rb_block_call_func
*iter
= inject_i
;
1014 switch (rb_scan_args(argc
, argv
, "02", &init
, &op
)) {
1019 if (rb_block_given_p()) {
1022 id
= rb_check_id(&init
);
1023 op
= id
? ID2SYM(id
) : init
;
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
);
1037 if (iter
== inject_op_i
&&
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
;
1051 partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, arys
))
1053 struct MEMO
*memo
= MEMO_CAST(arys
);
1057 if (RTEST(enum_yield(argc
, i
))) {
1063 rb_ary_push(ary
, i
);
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.
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.
1096 enum_partition(VALUE obj
)
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
);
1109 group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
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
);
1123 rb_ary_push(values
, i
);
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.
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.
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
);
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
;
1166 else if (FIXNUM_P(tally
) && tally
< INT2FIX(FIXNUM_MAX
)) {
1167 tally
+= INT2FIX(1) & ~FIXNUM_FLAG
;
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
);
1180 rb_enum_tally_up(VALUE hash
, VALUE group
)
1182 rb_hash_stlike_update(hash
, group
, tally_up
, (st_data_t
)hash
);
1187 tally_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
1190 rb_enum_tally_up(hash
, i
);
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.
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),
1210 * this may be useful for accumulating tallies across multiple enumerables:
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}
1223 enum_tally(int argc
, VALUE
*argv
, VALUE obj
)
1226 if (rb_check_arity(argc
, 0, 1)) {
1227 hash
= rb_to_hash_type(argv
[0]);
1228 rb_check_frozen(hash
);
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
)));
1239 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, params
))
1241 struct MEMO
*memo
= MEMO_CAST(params
);
1244 MEMO_V1_SET(memo
, i
);
1247 UNREACHABLE_RETURN(Qnil
);
1250 static VALUE
enum_take(VALUE obj
, VALUE n
);
1254 * first -> element or nil
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]
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) # => []
1278 enum_first(int argc
, VALUE
*argv
, VALUE obj
)
1281 rb_check_arity(argc
, 0, 1);
1283 return enum_take(obj
, argv
[0]);
1286 memo
= MEMO_NEW(Qnil
, 0, 0);
1287 rb_block_call(obj
, id_each
, 0, 0, first_i
, (VALUE
)memo
);
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>.
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.
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
{
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
;
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
);
1358 if (data
->n
== SORT_BY_BUFSIZE
) {
1359 rb_ary_concat(ary
, data
->buf
);
1366 sort_by_cmp(const void *ap
, const void *bp
, void *data
)
1368 struct cmp_opt_data cmp_opt
= { 0, 0 };
1371 VALUE ary
= (VALUE
)data
;
1373 if (RBASIC(ary
)->klass
) {
1374 rb_raise(rb_eRuntimeError
, "sort_by reentered");
1380 return OPTIMIZED_CMP(a
, b
, cmp_opt
);
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.
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
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 } }
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.
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
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|
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!
1466 enum_sort_by(VALUE obj
)
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);
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
);
1489 rb_block_call(obj
, id_each
, 0, 0, sort_by_i
, (VALUE
)memo
);
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
);
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); \
1521 name##_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1523 return enum_##name##_func(rb_enum_values_pack(argc, argv), MEMO_CAST(memo)); \
1527 name##_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1529 return enum_##name##_func(rb_yield_values2(argc, argv), MEMO_CAST(memo)); \
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)); \
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"); \
1548 DEFINE_ENUMFUNCS(all
)
1550 if (!RTEST(result
)) {
1551 MEMO_V1_SET(memo
, Qfalse
);
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
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?.
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
);
1609 DEFINE_ENUMFUNCS(any
)
1611 if (RTEST(result
)) {
1612 MEMO_V1_SET(memo
, Qtrue
);
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
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?.
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
);
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
);
1689 int (*cmpfunc
)(const void *, const void *, void *);
1690 int rev
: 1; /* max if 1 */
1691 int by
: 1; /* min_by if 1 */
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" : "");
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
);
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
);
1727 nmin_filter(struct nmin_data
*data
)
1739 if (data
->curlen
<= data
->n
)
1743 beg
= RARRAY_PTR(data
->buf
);
1744 eltsize
= data
->by
? 2 : 1;
1745 numelts
= data
->curlen
;
1750 #define GETPTR(i) (beg+(i)*eltsize)
1752 #define SWAP(i, j) do { \
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); \
1760 long pivot_index
= left
+ (right
-left
)/2;
1761 long num_pivots
= 1;
1763 SWAP(pivot_index
, right
);
1764 pivot_index
= right
;
1768 while (i
<= right
-num_pivots
) {
1769 int c
= data
->cmpfunc(GETPTR(i
), GETPTR(pivot_index
), data
);
1773 SWAP(i
, right
-num_pivots
);
1778 SWAP(i
, store_index
);
1784 for (i
= right
; right
-num_pivots
< i
; i
--) {
1791 if (store_index
<= n
&& n
<= store_index
+num_pivots
)
1794 if (n
< store_index
) {
1795 right
= store_index
-1;
1798 left
= store_index
+num_pivots
;
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
);
1810 nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _data
))
1812 struct nmin_data
*data
= (struct nmin_data
*)_data
;
1818 cmpv
= enum_yield(argc
, i
);
1822 if (data
->limit
!= Qundef
) {
1823 int c
= data
->cmpfunc(&cmpv
, &data
->limit
, data
);
1831 rb_ary_push(data
->buf
, cmpv
);
1832 rb_ary_push(data
->buf
, i
);
1836 if (data
->curlen
== data
->bufmax
) {
1844 rb_nmin_run(VALUE obj
, VALUE num
, int by
, int rev
, int ary
)
1847 struct nmin_data data
;
1849 data
.n
= NUM2LONG(num
);
1851 rb_raise(rb_eArgError
, "negative size (%ld)", data
.n
);
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;
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
:
1867 for (i
= 0; i
< RARRAY_LEN(obj
); i
++) {
1869 args
[0] = RARRAY_AREF(obj
, i
);
1870 nmin_i(obj
, (VALUE
)&data
, 1, args
, Qundef
);
1874 rb_block_call(obj
, id_each
, 0, 0, nmin_i
, (VALUE
)&data
);
1880 RARRAY_PTR_USE(result
, ptr
, {
1882 RARRAY_LEN(result
)/2,
1884 data
.cmpfunc
, (void *)&data
);
1885 for (i
=1; i
<RARRAY_LEN(result
); i
+=2) {
1889 rb_ary_resize(result
, RARRAY_LEN(result
)/2);
1892 RARRAY_PTR_USE(result
, ptr
, {
1893 ruby_qsort(ptr
, RARRAY_LEN(result
), sizeof(VALUE
),
1894 data
.cmpfunc
, (void *)&data
);
1898 rb_ary_reverse(result
);
1900 RBASIC_SET_CLASS(result
, rb_cArray
);
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?.
1949 enum_one(int argc
, VALUE
*argv
, VALUE obj
)
1951 struct MEMO
*memo
= MEMO_ENUM_NEW(Qundef
);
1954 WARN_UNUSED_BLOCK(argc
);
1955 rb_block_call(obj
, id_each
, 0, 0, ENUMFUNC(one
), (VALUE
)memo
);
1957 if (result
== Qundef
) return Qfalse
;
1961 DEFINE_ENUMFUNCS(none
)
1963 if (RTEST(result
)) {
1964 MEMO_V1_SET(memo
, Qfalse
);
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
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?.
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
);
2022 struct cmp_opt_data cmp_opt
;
2026 min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2028 struct min_t
*memo
= MEMO_FOR(struct min_t
, args
);
2032 if (memo
->min
== Qundef
) {
2036 if (OPTIMIZED_CMP(i
, memo
->min
, memo
->cmp_opt
) < 0) {
2044 min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2047 struct min_t
*memo
= MEMO_FOR(struct min_t
, args
);
2051 if (memo
->min
== Qundef
) {
2055 cmp
= rb_yield_values(2, i
, memo
->min
);
2056 if (rb_cmpint(cmp
, i
, memo
->min
) < 0) {
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:
2078 * (-4..-1).min # => -4
2079 * %w[d c b a].min # => "a"
2080 * {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1]
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]]
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.
2122 enum_min(int argc
, VALUE
*argv
, VALUE obj
)
2125 struct min_t
*m
= NEW_CMP_OPT_MEMO(struct min_t
, memo
);
2129 if (rb_check_arity(argc
, 0, 1) && !NIL_P(num
= argv
[0]))
2130 return rb_nmin_run(obj
, num
, 0, 0, 0);
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
);
2139 rb_block_call(obj
, id_each
, 0, 0, min_i
, memo
);
2142 if (result
== Qundef
) return Qnil
;
2148 struct cmp_opt_data cmp_opt
;
2152 max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2154 struct max_t
*memo
= MEMO_FOR(struct max_t
, args
);
2158 if (memo
->max
== Qundef
) {
2162 if (OPTIMIZED_CMP(i
, memo
->max
, memo
->cmp_opt
) > 0) {
2170 max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2172 struct max_t
*memo
= MEMO_FOR(struct max_t
, args
);
2177 if (memo
->max
== Qundef
) {
2181 cmp
= rb_yield_values(2, i
, memo
->max
);
2182 if (rb_cmpint(cmp
, i
, memo
->max
) > 0) {
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:
2203 * (-4..-1).max # => -1
2204 * %w[d c b a].max # => "d"
2205 * {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
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]]
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.
2247 enum_max(int argc
, VALUE
*argv
, VALUE obj
)
2250 struct max_t
*m
= NEW_CMP_OPT_MEMO(struct max_t
, memo
);
2254 if (rb_check_arity(argc
, 0, 1) && !NIL_P(num
= argv
[0]))
2255 return rb_nmin_run(obj
, num
, 0, 1, 0);
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
);
2264 rb_block_call(obj
, id_each
, 0, 0, max_i
, (VALUE
)memo
);
2267 if (result
== Qundef
) return Qnil
;
2275 struct cmp_opt_data cmp_opt
;
2279 minmax_i_update(VALUE i
, VALUE j
, struct minmax_t
*memo
)
2283 if (memo
->min
== Qundef
) {
2288 n
= OPTIMIZED_CMP(i
, memo
->min
, memo
->cmp_opt
);
2292 n
= OPTIMIZED_CMP(j
, memo
->max
, memo
->cmp_opt
);
2300 minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
2302 struct minmax_t
*memo
= MEMO_FOR(struct minmax_t
, _memo
);
2308 if (memo
->last
== Qundef
) {
2313 memo
->last
= Qundef
;
2315 n
= OPTIMIZED_CMP(j
, i
, memo
->cmp_opt
);
2325 minmax_i_update(i
, j
, memo
);
2331 minmax_ii_update(VALUE i
, VALUE j
, struct minmax_t
*memo
)
2335 if (memo
->min
== Qundef
) {
2340 n
= rb_cmpint(rb_yield_values(2, i
, memo
->min
), i
, memo
->min
);
2344 n
= rb_cmpint(rb_yield_values(2, j
, memo
->max
), j
, memo
->max
);
2352 minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
2354 struct minmax_t
*memo
= MEMO_FOR(struct minmax_t
, _memo
);
2360 if (memo
->last
== Qundef
) {
2365 memo
->last
= Qundef
;
2367 n
= rb_cmpint(rb_yield_values(2, j
, i
), j
, i
);
2377 minmax_ii_update(i
, j
, memo
);
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.
2414 enum_minmax(VALUE obj
)
2417 struct minmax_t
*m
= NEW_CMP_OPT_MEMO(struct minmax_t
, memo
);
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
);
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
);
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
);
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
);
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 }
2483 * %w[a b c d].min_by(2) {|element| -element.ord }
2485 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2486 * # => [[:baz, 2], [:bar, 1]]
2487 * [].min_by(2) {|element| -element }
2490 * Returns an Enumerator if no block is given.
2492 * Related: #min, #minmax, #max_by.
2497 enum_min_by(int argc
, VALUE
*argv
, VALUE obj
)
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
);
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
);
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
);
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 }
2558 * %w[a b c d].max_by(2) {|element| -element.ord }
2560 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2561 * # => [[:foo, 0], [:bar, 1]]
2562 * [].max_by(2) {|element| -element }
2565 * Returns an Enumerator if no block is given.
2567 * Related: #max, #minmax, #min_by.
2572 enum_max_by(int argc
, VALUE
*argv
, VALUE obj
)
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
);
2589 struct minmax_by_t
{
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
) {
2610 if (OPTIMIZED_CMP(v1
, memo
->min_bv
, cmp_opt
) < 0) {
2614 if (OPTIMIZED_CMP(v2
, memo
->max_bv
, cmp_opt
) > 0) {
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
);
2631 vi
= enum_yield(argc
, i
);
2633 if (memo
->last_bv
== Qundef
) {
2640 memo
->last_bv
= Qundef
;
2642 n
= OPTIMIZED_CMP(vj
, vi
, cmp_opt
);
2657 minmax_by_i_update(vi
, vj
, i
, j
, memo
);
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 }
2672 * %w[a b c d].minmax_by {|element| -element.ord }
2674 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2675 * # => [[:baz, 2], [:foo, 0]]
2676 * [].minmax_by {|element| -element }
2679 * Returns an Enumerator if no block is given.
2681 * Related: #max_by, #minmax, #min_by.
2686 enum_minmax_by(VALUE obj
)
2689 struct minmax_by_t
*m
= NEW_MEMO_FOR(struct minmax_by_t
, memo
);
2691 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
2697 m
->last_bv
= 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
);
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
);
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?.
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
);
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
);
2753 return rb_yield_values(2, rb_enum_values_pack(argc
, argv
), n
);
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;
2765 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
2766 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
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}
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.
2784 enum_each_with_index(int argc
, VALUE
*argv
, VALUE obj
)
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
);
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+:
2805 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
2806 * a # => [-4, -3, -2, -1]
2809 * %w[a b c d].reverse_each {|element| a.push(element) }
2810 * # => ["a", "b", "c", "d"]
2811 * a # => ["d", "c", "b", "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.
2823 enum_reverse_each(int argc
, VALUE
*argv
, VALUE obj
)
2828 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
2830 ary
= enum_to_a(argc
, argv
, obj
);
2832 len
= RARRAY_LEN(ary
);
2835 rb_yield(RARRAY_AREF(ary
, len
));
2836 nlen
= RARRAY_LEN(ary
);
2847 each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
2850 enum_yield(argc
, i
);
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+:
2863 * (1..4).each_entry {|element| a.push(element) } # => 1..4
2864 * a # => [1, 2, 3, 4]
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]]
2873 * include Enumerable
2880 * Foo.new.each_entry {|yielded| p yielded }
2888 * With no block given, returns an Enumerator.
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);
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
);
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)
2919 each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, m
))
2921 struct MEMO
*memo
= MEMO_CAST(m
);
2922 VALUE ary
= memo
->v1
;
2924 long size
= memo
->u3
.cnt
;
2927 rb_ary_push(ary
, i
);
2929 if (RARRAY_LEN(ary
) == size
) {
2933 MEMO_V1_SET(memo
, rb_ary_new2(size
));
2944 enum_each_slice_size(VALUE obj
, VALUE args
, VALUE eobj
)
2947 long slice_size
= NUM2LONG(RARRAY_AREF(args
, 0));
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))) {
2958 n
= add_int(size
, slice_size
-1);
2959 return div_int(n
, slice_size
);
2964 * each_slice(n) { ... } -> self
2965 * each_slice(n) -> enumerator
2967 * Calls the block with each successive disjoint +n+-tuple of elements;
2971 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
2972 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
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.
2983 enum_each_slice(VALUE obj
, VALUE n
)
2985 long size
= NUM2LONG(n
);
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
);
2998 if (RARRAY_LEN(ary
) > 0) rb_yield(ary
);
3004 each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3006 struct MEMO
*memo
= MEMO_CAST(args
);
3007 VALUE ary
= memo
->v1
;
3009 long size
= memo
->u3
.cnt
;
3012 if (RARRAY_LEN(ary
) == size
) {
3015 rb_ary_push(ary
, i
);
3016 if (RARRAY_LEN(ary
) == size
) {
3018 ary
= rb_ary_dup(ary
);
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);
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
;
3043 * each_cons(n) { ... } -> self
3044 * each_cons(n) -> enumerator
3046 * Calls the block with each successive overlapped +n+-tuple of elements;
3050 * (1..5).each_cons(3) {|element| a.push(element) }
3051 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
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.
3062 enum_each_cons(VALUE obj
, VALUE n
)
3064 long size
= NUM2LONG(n
);
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
);
3079 each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memo
))
3082 return rb_yield_values(2, i
, memo
);
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.
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
);
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
++;
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
);
3129 rb_ary_push(tmp
, RARRAY_AREF(e
, n
));
3132 if (NIL_P(result
)) {
3133 enum_yield_array(tmp
);
3136 rb_ary_push(result
, tmp
);
3147 VALUE
*v
= (VALUE
*)w
;
3148 return v
[0] = rb_funcallv(v
[1], id_next
, 0, 0);
3152 call_stop(VALUE w
, VALUE _
)
3154 VALUE
*v
= (VALUE
*)w
;
3155 return v
[0] = Qundef
;
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
;
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
);
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
);
3182 rb_ary_push(tmp
, v
[0]);
3185 if (NIL_P(result
)) {
3186 enum_yield_array(tmp
);
3189 rb_ary_push(result
, tmp
);
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]
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}
3224 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3225 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3226 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
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]
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]
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
3265 enum_zip(int argc
, VALUE
*argv
, VALUE obj
)
3270 VALUE result
= Qnil
;
3271 VALUE args
= rb_ary_new4(argc
, argv
);
3274 argv
= RARRAY_PTR(args
);
3275 for (i
=0; i
<argc
; i
++) {
3276 VALUE ary
= rb_check_array_type(argv
[i
]);
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
);
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();
3318 * For non-negative integer +n+, returns the first +n+ elements:
3321 * r.take(2) # => [1, 2]
3324 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3325 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3330 enum_take(VALUE obj
, VALUE n
)
3334 long len
= NUM2LONG(n
);
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
);
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
));
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.
3376 enum_take_while(VALUE obj
)
3380 RETURN_ENUMERATOR(obj
, 0, 0);
3382 rb_block_call(obj
, id_each
, 0, 0, take_while_i
, ary
);
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
));
3403 * For positive integer +n+, returns an array containing
3404 * all but the first +n+ elements:
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]]
3419 enum_drop(VALUE obj
, VALUE n
)
3423 long len
= NUM2LONG(n
);
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
);
3437 drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3439 struct MEMO
*memo
= MEMO_CAST(args
);
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
);
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.
3471 enum_drop_while(VALUE obj
)
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
);
3484 cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
3488 rb_ary_push(ary
, argc
> 1 ? i
: rb_ary_new_from_values(argc
, argv
));
3489 enum_yield(argc
, i
);
3494 enum_cycle_size(VALUE self
, VALUE args
, VALUE eobj
)
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);
3511 return rb_funcallv(size
, '*', 1, &n
);
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+:
3524 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3525 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3527 * ('a'..'d').cycle(2) {|element| a.push(element) }
3528 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
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.
3542 enum_cycle(int argc
, VALUE
*argv
, VALUE obj
)
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])) {
3556 if (n
<= 0) return Qnil
;
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
));
3579 chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _argp
))
3581 struct chunk_arg
*argp
= MEMO_FOR(struct chunk_arg
, _argp
);
3583 VALUE alone
= ID2SYM(id__alone
);
3584 VALUE separator
= ID2SYM(id__separator
);
3588 v
= rb_funcallv(argp
->categorize
, id_call
, 1, &i
);
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");
3610 if (NIL_P(argp
->prev_value
)) {
3611 argp
->prev_value
= v
;
3612 argp
->prev_elts
= rb_ary_new3(1, i
);
3615 if (rb_equal(argp
->prev_value
, v
)) {
3616 rb_ary_push(argp
->prev_elts
, i
);
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
);
3630 chunk_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
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
);
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:
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.
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' }
3697 * You can use the special symbol <tt>:_alone</tt> to force an element
3698 * into its own separate chuck:
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:
3707 * open(filename) { |f|
3708 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, 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|
3731 * line != sep || nil
3732 * }.each { |_, lines|
3736 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
3738 * # "* README, README.ja: Update the portability section.\n",
3740 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
3742 * # "* README, README.ja: Add a note about default C flags.\n",
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|
3756 enum_chunk(VALUE enumerable
)
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
);
3770 struct slicebefore_arg
{
3778 slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _argp
))
3780 struct slicebefore_arg
*argp
= MEMO_FOR(struct slicebefore_arg
, _argp
);
3785 if (!NIL_P(argp
->sep_pat
))
3786 header_p
= rb_funcallv(argp
->sep_pat
, id_eqq
, 1, &i
);
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
);
3795 if (NIL_P(argp
->prev_elts
))
3796 argp
->prev_elts
= rb_ary_new3(1, i
);
3798 rb_ary_push(argp
->prev_elts
, i
);
3805 slicebefore_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
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
);
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 }
3841 * ["bar", "fop", "for"]
3842 * ["baz", "fob", "fog"]
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 }
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
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"]
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]
3897 * p a.slice_before { |e|
3898 * prev, prev2 = e, prev
3901 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
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.
3915 * words.slice_before { |w|
3916 * cols += 1 if cols != 0
3918 * if maxwidth < cols
3924 * }.each {|ws| y.yield ws }
3927 * text = (1..20).to_a.join(" ")
3928 * enum = wordwrap(text.split(/\s+/), 10)
3930 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
3932 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
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.
3954 * open("mbox") { |f|
3955 * f.slice_before { |line|
3956 * line.start_with? "From "
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
3970 * # split mails in mbox (slice before Unix From line after an empty line)
3971 * open("mbox") { |f|
3973 * f.slice_before { |line|
3975 * emp = line == "\n"
3976 * prevemp && line.start_with?("From ")
3978 * mail.pop if mail.last == "\n"
3985 enum_slice_before(int argc
, VALUE
*argv
, VALUE enumerable
)
3989 if (rb_block_given_p()) {
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());
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
);
4007 struct sliceafter_arg
{
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
;
4024 if (NIL_P(memo
->prev_elts
)) {
4025 memo
->prev_elts
= rb_ary_new3(1, i
);
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
));
4036 split_p
= RTEST(rb_funcallv(memo
->pred
, id_call
, 1, &i
));
4041 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4043 memo
->prev_elts
= Qnil
;
4051 sliceafter_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
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
);
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 }
4086 * ["fop", "for", "baz"]
4087 * ["fob", "fog", "bam"]
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 }
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/)
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"]
4122 enum_slice_after(int argc
, VALUE
*argv
, VALUE enumerable
)
4125 VALUE pat
= Qnil
, pred
= Qnil
;
4127 if (rb_block_given_p()) {
4129 rb_raise(rb_eArgError
, "both pattern and block are given");
4130 pred
= rb_block_proc();
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
);
4145 struct slicewhen_arg
{
4150 int inverted
; /* 0 for slice_when and 1 for chunk_while. */
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
;
4163 if (memo
->prev_elt
== Qundef
) {
4164 /* The first element */
4166 memo
->prev_elts
= rb_ary_new3(1, i
);
4170 args
[0] = memo
->prev_elt
;
4172 split_p
= RTEST(rb_funcallv(memo
->pred
, id_call
, 2, args
));
4179 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4181 memo
->prev_elts
= rb_ary_new3(1, i
);
4184 rb_ary_push(memo
->prev_elts
, i
);
4195 slicewhen_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
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
);
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 }
4237 enum_slice_when(VALUE enumerable
)
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
);
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:
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 }
4278 enum_chunk_while(VALUE enumerable
)
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
);
4294 struct enum_sum_memo
{
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
);
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 ...? */
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
);
4328 sum_iter_bignum(VALUE i
, struct enum_sum_memo
*memo
)
4330 memo
->v
= rb_big_plus(i
, memo
->v
);
4334 sum_iter_rational(VALUE i
, struct enum_sum_memo
*memo
)
4336 if (memo
->r
== Qundef
) {
4340 memo
->r
= rb_rational_plus(memo
->r
, i
);
4345 sum_iter_some_value(VALUE i
, struct enum_sum_memo
*memo
)
4347 memo
->v
= rb_funcallv(memo
->v
, idPLUS
, 1, &i
);
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
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;
4365 memo
->v
= DBL2NUM(memo
->f
);
4366 memo
->float_value
= 0;
4367 sum_iter_some_value(i
, memo
);
4376 else if (! isfinite(x
)) {
4377 if (isinf(x
) && isinf(f
) && signbit(x
) != signbit(f
)) {
4385 else if (isinf(f
)) {
4392 if (fabs(f
) >= fabs(x
)) {
4405 sum_iter(VALUE i
, struct enum_sum_memo
*memo
)
4407 assert(memo
!= NULL
);
4408 if (memo
->block_given
) {
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;
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;
4426 sum_iter_normalize_memo(memo
);
4427 memo
->f
= NUM2DBL(memo
->v
);
4429 memo
->float_value
= 1;
4430 sum_iter_Kahan_Babuska(i
, memo
);
4433 sum_iter_normalize_memo(memo
);
4434 sum_iter_some_value(i
, memo
);
4441 enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
4444 sum_iter(i
, (struct enum_sum_memo
*) args
);
4449 hash_sum_i(VALUE key
, VALUE value
, VALUE arg
)
4451 sum_iter(rb_assoc_new(key
, value
), (struct enum_sum_memo
*) arg
);
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
);
4465 int_range_sum(VALUE beg
, VALUE end
, int excl
, VALUE init
)
4469 end
= LONG2FIX(FIX2LONG(end
) - 1);
4471 end
= rb_big_minus(end
, LONG2FIX(1));
4474 if (rb_int_ge(end
, beg
)) {
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
);
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"
4517 enum_sum(int argc
, VALUE
* argv
, VALUE obj
)
4519 struct enum_sum_memo memo
;
4523 memo
.v
= (rb_check_arity(argc
, 0, 1) == 0) ? LONG2FIX(0) : argv
[0];
4524 memo
.block_given
= rb_block_given_p();
4528 if ((memo
.float_value
= RB_FLOAT_TYPE_P(memo
.v
))) {
4529 memo
.f
= RFLOAT_VALUE(memo
.v
);
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
);
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
);
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
);
4565 uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
4568 rb_hash_add_new_element(hash
, i
, i
);
4573 uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
4576 rb_hash_add_new_element(hash
, rb_yield_values2(argc
, argv
), i
);
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"]
4602 enum_uniq(VALUE obj
)
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
);
4616 compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
4621 rb_ary_push(ary
, i
);
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]
4638 enum_compact(VALUE obj
)
4643 rb_block_call(obj
, id_each
, 0, 0, compact_i
, ary
);
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.
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.
4752 * To use module \Enumerable in a collection class:
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.
4765 * include Enumerable
4772 * Foo.new.each_entry{ |element| p element }
4780 * == \Enumerable in Ruby Classes
4782 * These Ruby core classes include (or extend) \Enumerable:
4794 * These Ruby standard library classes include \Enumerable:
4801 * Virtually all methods in \Enumerable call method +#each+ in the including class:
4803 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element \Array.
4804 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element \Array.
4805 * - For the other classes above, +#each+ yields the next object from the collection.
4807 * == About the Examples
4809 * The example code snippets for the \Enumerable methods:
4811 * - Always show the use of one or more \Array-like classes (often \Array itself).
4812 * - Sometimes show the use of a \Hash-like class.
4813 * For some methods, though, the usage would not make sense,
4814 * and so it is not shown. Example: #tally would find exactly one of each \Hash entry.
4819 Init_Enumerable(void)
4821 rb_mEnumerable
= rb_define_module("Enumerable");
4823 rb_define_method(rb_mEnumerable
, "to_a", enum_to_a
, -1);
4824 rb_define_method(rb_mEnumerable
, "entries", enum_to_a
, -1);
4825 rb_define_method(rb_mEnumerable
, "to_h", enum_to_h
, -1);
4827 rb_define_method(rb_mEnumerable
, "sort", enum_sort
, 0);
4828 rb_define_method(rb_mEnumerable
, "sort_by", enum_sort_by
, 0);
4829 rb_define_method(rb_mEnumerable
, "grep", enum_grep
, 1);
4830 rb_define_method(rb_mEnumerable
, "grep_v", enum_grep_v
, 1);
4831 rb_define_method(rb_mEnumerable
, "count", enum_count
, -1);
4832 rb_define_method(rb_mEnumerable
, "find", enum_find
, -1);
4833 rb_define_method(rb_mEnumerable
, "detect", enum_find
, -1);
4834 rb_define_method(rb_mEnumerable
, "find_index", enum_find_index
, -1);
4835 rb_define_method(rb_mEnumerable
, "find_all", enum_find_all
, 0);
4836 rb_define_method(rb_mEnumerable
, "select", enum_find_all
, 0);
4837 rb_define_method(rb_mEnumerable
, "filter", enum_find_all
, 0);
4838 rb_define_method(rb_mEnumerable
, "filter_map", enum_filter_map
, 0);
4839 rb_define_method(rb_mEnumerable
, "reject", enum_reject
, 0);
4840 rb_define_method(rb_mEnumerable
, "collect", enum_collect
, 0);
4841 rb_define_method(rb_mEnumerable
, "map", enum_collect
, 0);
4842 rb_define_method(rb_mEnumerable
, "flat_map", enum_flat_map
, 0);
4843 rb_define_method(rb_mEnumerable
, "collect_concat", enum_flat_map
, 0);
4844 rb_define_method(rb_mEnumerable
, "inject", enum_inject
, -1);
4845 rb_define_method(rb_mEnumerable
, "reduce", enum_inject
, -1);
4846 rb_define_method(rb_mEnumerable
, "partition", enum_partition
, 0);
4847 rb_define_method(rb_mEnumerable
, "group_by", enum_group_by
, 0);
4848 rb_define_method(rb_mEnumerable
, "tally", enum_tally
, -1);
4849 rb_define_method(rb_mEnumerable
, "first", enum_first
, -1);
4850 rb_define_method(rb_mEnumerable
, "all?", enum_all
, -1);
4851 rb_define_method(rb_mEnumerable
, "any?", enum_any
, -1);
4852 rb_define_method(rb_mEnumerable
, "one?", enum_one
, -1);
4853 rb_define_method(rb_mEnumerable
, "none?", enum_none
, -1);
4854 rb_define_method(rb_mEnumerable
, "min", enum_min
, -1);
4855 rb_define_method(rb_mEnumerable
, "max", enum_max
, -1);
4856 rb_define_method(rb_mEnumerable
, "minmax", enum_minmax
, 0);
4857 rb_define_method(rb_mEnumerable
, "min_by", enum_min_by
, -1);
4858 rb_define_method(rb_mEnumerable
, "max_by", enum_max_by
, -1);
4859 rb_define_method(rb_mEnumerable
, "minmax_by", enum_minmax_by
, 0);
4860 rb_define_method(rb_mEnumerable
, "member?", enum_member
, 1);
4861 rb_define_method(rb_mEnumerable
, "include?", enum_member
, 1);
4862 rb_define_method(rb_mEnumerable
, "each_with_index", enum_each_with_index
, -1);
4863 rb_define_method(rb_mEnumerable
, "reverse_each", enum_reverse_each
, -1);
4864 rb_define_method(rb_mEnumerable
, "each_entry", enum_each_entry
, -1);
4865 rb_define_method(rb_mEnumerable
, "each_slice", enum_each_slice
, 1);
4866 rb_define_method(rb_mEnumerable
, "each_cons", enum_each_cons
, 1);
4867 rb_define_method(rb_mEnumerable
, "each_with_object", enum_each_with_object
, 1);
4868 rb_define_method(rb_mEnumerable
, "zip", enum_zip
, -1);
4869 rb_define_method(rb_mEnumerable
, "take", enum_take
, 1);
4870 rb_define_method(rb_mEnumerable
, "take_while", enum_take_while
, 0);
4871 rb_define_method(rb_mEnumerable
, "drop", enum_drop
, 1);
4872 rb_define_method(rb_mEnumerable
, "drop_while", enum_drop_while
, 0);
4873 rb_define_method(rb_mEnumerable
, "cycle", enum_cycle
, -1);
4874 rb_define_method(rb_mEnumerable
, "chunk", enum_chunk
, 0);
4875 rb_define_method(rb_mEnumerable
, "slice_before", enum_slice_before
, -1);
4876 rb_define_method(rb_mEnumerable
, "slice_after", enum_slice_after
, -1);
4877 rb_define_method(rb_mEnumerable
, "slice_when", enum_slice_when
, 0);
4878 rb_define_method(rb_mEnumerable
, "chunk_while", enum_chunk_while
, 0);
4879 rb_define_method(rb_mEnumerable
, "sum", enum_sum
, -1);
4880 rb_define_method(rb_mEnumerable
, "uniq", enum_uniq
, 0);
4881 rb_define_method(rb_mEnumerable
, "compact", enum_compact
, 0);
4883 id__alone
= rb_intern_const("_alone");
4884 id__separator
= rb_intern_const("_separator");
4885 id_chunk_categorize
= rb_intern_const("chunk_categorize");
4886 id_chunk_enumerable
= rb_intern_const("chunk_enumerable");
4887 id_next
= rb_intern_const("next");
4888 id_sliceafter_enum
= rb_intern_const("sliceafter_enum");
4889 id_sliceafter_pat
= rb_intern_const("sliceafter_pat");
4890 id_sliceafter_pred
= rb_intern_const("sliceafter_pred");
4891 id_slicebefore_enumerable
= rb_intern_const("slicebefore_enumerable");
4892 id_slicebefore_sep_pat
= rb_intern_const("slicebefore_sep_pat");
4893 id_slicebefore_sep_pred
= rb_intern_const("slicebefore_sep_pred");
4894 id_slicewhen_enum
= rb_intern_const("slicewhen_enum");
4895 id_slicewhen_inverted
= rb_intern_const("slicewhen_inverted");
4896 id_slicewhen_pred
= rb_intern_const("slicewhen_pred");