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
);
703 * to_a(*args) -> array
705 * Returns an array containing the items in +self+:
707 * (0..4).to_a # => [0, 1, 2, 3, 4]
711 enum_to_a(int argc
, VALUE
*argv
, VALUE obj
)
713 VALUE ary
= rb_ary_new();
715 rb_block_call_kw(obj
, id_each
, argc
, argv
, collect_all
, ary
, RB_PASS_CALLED_KEYWORDS
);
721 enum_hashify_into(VALUE obj
, int argc
, const VALUE
*argv
, rb_block_call_func
*iter
, VALUE hash
)
723 rb_block_call(obj
, id_each
, argc
, argv
, iter
, hash
);
728 enum_hashify(VALUE obj
, int argc
, const VALUE
*argv
, rb_block_call_func
*iter
)
730 return enum_hashify_into(obj
, argc
, argv
, iter
, rb_hash_new());
734 enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
737 return rb_hash_set_pair(hash
, i
);
741 enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
743 return rb_hash_set_pair(hash
, rb_yield_values2(argc
, argv
));
748 * to_h(*args) -> hash
749 * to_h(*args) {|element| ... } -> hash
751 * When +self+ consists of 2-element arrays,
752 * returns a hash each of whose entries is the key-value pair
753 * formed from one of those arrays:
755 * [[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
757 * When a block is given, the block is called with each element of +self+;
758 * the block should return a 2-element array which becomes a key-value pair
759 * in the returned hash:
761 * (0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
763 * Raises an exception if an element of +self+ is not a 2-element array,
764 * and a block is not passed.
768 enum_to_h(int argc
, VALUE
*argv
, VALUE obj
)
770 rb_block_call_func
*iter
= rb_block_given_p() ? enum_to_h_ii
: enum_to_h_i
;
771 return enum_hashify(obj
, argc
, argv
, iter
);
775 inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
777 struct MEMO
*memo
= MEMO_CAST(p
);
781 if (UNDEF_P(memo
->v1
)) {
782 MEMO_V1_SET(memo
, i
);
785 MEMO_V1_SET(memo
, rb_yield_values(2, memo
->v1
, i
));
791 inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
793 struct MEMO
*memo
= MEMO_CAST(p
);
798 if (UNDEF_P(memo
->v1
)) {
799 MEMO_V1_SET(memo
, i
);
801 else if (SYMBOL_P(name
= memo
->u3
.value
)) {
802 const ID mid
= SYM2ID(name
);
803 MEMO_V1_SET(memo
, rb_funcallv_public(memo
->v1
, mid
, 1, &i
));
809 MEMO_V1_SET(memo
, rb_f_send(numberof(args
), args
, memo
->v1
));
815 ary_inject_op(VALUE ary
, VALUE init
, VALUE op
)
821 if (RARRAY_LEN(ary
) == 0)
822 return UNDEF_P(init
) ? Qnil
: init
;
825 v
= RARRAY_AREF(ary
, 0);
827 if (RARRAY_LEN(ary
) == 1)
837 if (RB_INTEGER_TYPE_P(v
) &&
838 rb_method_basic_definition_p(rb_cInteger
, idPLUS
) &&
839 rb_obj_respond_to(v
, idPLUS
, FALSE
)) {
841 for (; i
< RARRAY_LEN(ary
); i
++) {
842 e
= RARRAY_AREF(ary
, i
);
844 n
+= FIX2LONG(e
); /* should not overflow long type */
846 v
= rb_big_plus(LONG2NUM(n
), v
);
850 else if (RB_BIGNUM_TYPE_P(e
))
851 v
= rb_big_plus(e
, v
);
856 v
= rb_fix_plus(LONG2FIX(n
), v
);
861 v
= rb_fix_plus(LONG2FIX(n
), v
);
864 for (; i
< RARRAY_LEN(ary
); i
++) {
865 VALUE arg
= RARRAY_AREF(ary
, i
);
866 v
= rb_funcallv_public(v
, id
, 1, &arg
);
873 * inject(symbol) -> object
874 * inject(initial_value, symbol) -> object
875 * inject {|memo, value| ... } -> object
876 * inject(initial_value) {|memo, value| ... } -> object
878 * Returns the result of applying a reducer to an initial value and
879 * the first element of the Enumerable. It then takes the result and applies the
880 * function to it and the second element of the collection, and so on. The
881 * return value is the result returned by the final call to the function.
885 * [ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
889 * fn(fn(fn(fn(i, a), b), c), d)
891 * In a way the +inject+ function _injects_ the function
892 * between the elements of the enumerable.
894 * +inject+ is aliased as +reduce+. You use it when you want to
895 * _reduce_ a collection to a single value.
897 * <b>The Calling Sequences</b>
899 * Let's start with the most verbose:
901 * enum.inject(initial_value) do |result, next_value|
902 * # do something with +result+ and +next_value+
903 * # the value returned by the block becomes the
904 * # value passed in to the next iteration
910 * product = [ 2, 3, 4 ].inject(1) do |result, next_value|
911 * result * next_value
915 * When this runs, the block is first called with +1+ (the initial value) and
916 * +2+ (the first element of the array). The block returns <tt>1*2</tt>, so on
917 * the next iteration the block is called with +2+ (the previous result) and
918 * +3+. The block returns +6+, and is called one last time with +6+ and +4+.
919 * The result of the block, +24+ becomes the value returned by +inject+. This
920 * code returns the product of the elements in the enumerable.
922 * <b>First Shortcut: Default Initial value</b>
924 * In the case of the previous example, the initial value, +1+, wasn't really
925 * necessary: the calculation of the product of a list of numbers is self-contained.
927 * In these circumstances, you can omit the +initial_value+ parameter. +inject+
928 * will then initially call the block with the first element of the collection
929 * as the +result+ parameter and the second element as the +next_value+.
931 * [ 2, 3, 4 ].inject do |result, next_value|
932 * result * next_value
935 * This shortcut is convenient, but can only be used when the block produces a result
936 * which can be passed back to it as a first parameter.
938 * Here's an example where that's not the case: it returns a hash where the keys are words
939 * and the values are the number of occurrences of that word in the enumerable.
941 * freqs = File.read("README.md")
943 * .reduce(Hash.new(0)) do |counts, word|
947 * freqs #=> {"Actions"=>4,
954 * Note that the last line of the block is just the word +counts+. This ensures the
955 * return value of the block is the result that's being calculated.
957 * <b>Second Shortcut: a Reducer function</b>
959 * A <i>reducer function</i> is a function that takes a partial result and the next value,
960 * returning the next partial result. The block that is given to +inject+ is a reducer.
962 * You can also write a reducer as a function and pass the name of that function
963 * (as a symbol) to +inject+. However, for this to work, the function
965 * 1. Must be defined on the type of the result value
966 * 2. Must accept a single parameter, the next value in the collection, and
967 * 3. Must return an updated result which will also implement the function.
969 * Here's an example that adds elements to a string. The two calls invoke the functions
970 * String#concat and String#+ on the result so far, passing it the next value.
972 * s = [ "cat", " ", "dog" ].inject("", :concat)
974 * s = [ "cat", " ", "dog" ].inject("The result is:", :+)
975 * s #=> "The result is: cat dog"
977 * Here's a more complex example when the result object maintains
978 * state of a different type to the enumerable elements.
988 * when "n" then @y += 1
989 * when "s" then @y -= 1
990 * when "e" then @x += 1
991 * when "w" then @x -= 1
997 * position = "nnneesw".chars.reduce(Turtle.new, :move)
998 * position #=>> #<Turtle:0x00000001052f4698 @y=2, @x=1>
1000 * <b>Third Shortcut: Reducer With no Initial Value</b>
1002 * If your reducer returns a value that it can accept as a parameter, then you
1003 * don't have to pass in an initial value. Here <tt>:*</tt> is the name of the
1006 * product = [ 2, 3, 4 ].inject(:*)
1009 * String concatenation again:
1011 * s = [ "cat", " ", "dog" ].inject(:+)
1014 * And an example that converts a hash to an array of two-element subarrays.
1016 * nested = {foo: 0, bar: 1}.inject([], :push)
1017 * nested # => [[:foo, 0], [:bar, 1]]
1022 enum_inject(int argc
, VALUE
*argv
, VALUE obj
)
1026 rb_block_call_func
*iter
= inject_i
;
1030 if (rb_block_given_p()) {
1031 num_args
= rb_scan_args(argc
, argv
, "02", &init
, &op
);
1034 num_args
= rb_scan_args(argc
, argv
, "11", &init
, &op
);
1042 if (rb_block_given_p()) {
1045 id
= rb_check_id(&init
);
1046 op
= id
? ID2SYM(id
) : init
;
1051 if (rb_block_given_p()) {
1052 rb_warning("given block not used");
1054 id
= rb_check_id(&op
);
1055 if (id
) op
= ID2SYM(id
);
1060 if (iter
== inject_op_i
&&
1062 RB_TYPE_P(obj
, T_ARRAY
) &&
1063 rb_method_basic_definition_p(CLASS_OF(obj
), id_each
)) {
1064 return ary_inject_op(obj
, init
, op
);
1067 memo
= MEMO_NEW(init
, Qnil
, op
);
1068 rb_block_call(obj
, id_each
, 0, 0, iter
, (VALUE
)memo
);
1069 if (UNDEF_P(memo
->v1
)) return Qnil
;
1074 partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, arys
))
1076 struct MEMO
*memo
= MEMO_CAST(arys
);
1080 if (RTEST(enum_yield(argc
, i
))) {
1086 rb_ary_push(ary
, i
);
1092 * partition {|element| ... } -> [true_array, false_array]
1093 * partition -> enumerator
1095 * With a block given, returns an array of two arrays:
1097 * - The first having those elements for which the block returns a truthy value.
1098 * - The other having all other elements.
1102 * p = (1..4).partition {|i| i.even? }
1103 * p # => [[2, 4], [1, 3]]
1104 * p = ('a'..'d').partition {|c| c < 'c' }
1105 * p # => [["a", "b"], ["c", "d"]]
1106 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
1107 * p = h.partition {|key, value| key.start_with?('b') }
1108 * p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
1109 * p = h.partition {|key, value| value < 2 }
1110 * p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]
1112 * With no block given, returns an Enumerator.
1114 * Related: Enumerable#group_by.
1119 enum_partition(VALUE obj
)
1123 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
1125 memo
= MEMO_NEW(rb_ary_new(), rb_ary_new(), 0);
1126 rb_block_call(obj
, id_each
, 0, 0, partition_i
, (VALUE
)memo
);
1128 return rb_assoc_new(memo
->v1
, memo
->v2
);
1132 group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
1139 group
= enum_yield(argc
, i
);
1140 values
= rb_hash_aref(hash
, group
);
1141 if (!RB_TYPE_P(values
, T_ARRAY
)) {
1142 values
= rb_ary_new3(1, i
);
1143 rb_hash_aset(hash
, group
, values
);
1146 rb_ary_push(values
, i
);
1153 * group_by {|element| ... } -> hash
1154 * group_by -> enumerator
1156 * With a block given returns a hash:
1158 * - Each key is a return value from the block.
1159 * - Each value is an array of those elements for which the block returned that key.
1163 * g = (1..6).group_by {|i| i%3 }
1164 * g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]}
1165 * h = {foo: 0, bar: 1, baz: 0, bat: 1}
1166 * g = h.group_by {|key, value| value }
1167 * g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
1169 * With no block given, returns an Enumerator.
1174 enum_group_by(VALUE obj
)
1176 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
1178 return enum_hashify(obj
, 0, 0, group_by_i
);
1182 tally_up(st_data_t
*group
, st_data_t
*value
, st_data_t arg
, int existing
)
1184 VALUE tally
= (VALUE
)*value
;
1185 VALUE hash
= (VALUE
)arg
;
1189 else if (FIXNUM_P(tally
) && tally
< INT2FIX(FIXNUM_MAX
)) {
1190 tally
+= INT2FIX(1) & ~FIXNUM_FLAG
;
1193 Check_Type(tally
, T_BIGNUM
);
1194 tally
= rb_big_plus(tally
, INT2FIX(1));
1195 RB_OBJ_WRITTEN(hash
, Qundef
, tally
);
1197 *value
= (st_data_t
)tally
;
1198 if (!SPECIAL_CONST_P(*group
)) RB_OBJ_WRITTEN(hash
, Qundef
, *group
);
1203 rb_enum_tally_up(VALUE hash
, VALUE group
)
1205 rb_hash_stlike_update(hash
, group
, tally_up
, (st_data_t
)hash
);
1210 tally_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
1213 rb_enum_tally_up(hash
, i
);
1220 * tally(hash) -> hash
1222 * Returns a hash containing the counts of equal elements:
1224 * - Each key is an element of +self+.
1225 * - Each value is the number elements equal to that key.
1229 * %w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}
1231 * With a hash argument, that hash is used for the tally (instead of a new hash),
1233 * this may be useful for accumulating tallies across multiple enumerables:
1236 * hash = %w[a c d b c a].tally(hash)
1237 * hash # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1}
1238 * hash = %w[b a z].tally(hash)
1239 * hash # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1}
1240 * hash = %w[b a m].tally(hash)
1241 * hash # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=> 1}
1246 enum_tally(int argc
, VALUE
*argv
, VALUE obj
)
1249 if (rb_check_arity(argc
, 0, 1)) {
1250 hash
= rb_to_hash_type(argv
[0]);
1251 rb_check_frozen(hash
);
1254 hash
= rb_hash_new();
1257 return enum_hashify_into(obj
, 0, 0, tally_i
, hash
);
1260 NORETURN(static VALUE
first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, params
)));
1262 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, params
))
1264 struct MEMO
*memo
= MEMO_CAST(params
);
1267 MEMO_V1_SET(memo
, i
);
1270 UNREACHABLE_RETURN(Qnil
);
1273 static VALUE
enum_take(VALUE obj
, VALUE n
);
1277 * first -> element or nil
1280 * Returns the first element or elements.
1282 * With no argument, returns the first element, or +nil+ if there is none:
1284 * (1..4).first # => 1
1285 * %w[a b c].first # => "a"
1286 * {foo: 1, bar: 1, baz: 2}.first # => [:foo, 1]
1289 * With integer argument +n+, returns an array
1290 * containing the first +n+ elements that exist:
1292 * (1..4).first(2) # => [1, 2]
1293 * %w[a b c d].first(3) # => ["a", "b", "c"]
1294 * %w[a b c d].first(50) # => ["a", "b", "c", "d"]
1295 * {foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]]
1296 * [].first(2) # => []
1301 enum_first(int argc
, VALUE
*argv
, VALUE obj
)
1304 rb_check_arity(argc
, 0, 1);
1306 return enum_take(obj
, argv
[0]);
1309 memo
= MEMO_NEW(Qnil
, 0, 0);
1310 rb_block_call(obj
, id_each
, 0, 0, first_i
, (VALUE
)memo
);
1318 * sort {|a, b| ... } -> array
1320 * Returns an array containing the sorted elements of +self+.
1321 * The ordering of equal elements is indeterminate and may be unstable.
1323 * With no block given, the sort compares
1324 * using the elements' own method <tt><=></tt>:
1326 * %w[b c a d].sort # => ["a", "b", "c", "d"]
1327 * {foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]
1329 * With a block given, comparisons in the block determine the ordering.
1330 * The block is called with two elements +a+ and +b+, and must return:
1332 * - A negative integer if <tt>a < b</tt>.
1333 * - Zero if <tt>a == b</tt>.
1334 * - A positive integer if <tt>a > b</tt>.
1339 * a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"]
1340 * h = {foo: 0, bar: 1, baz: 2}
1341 * h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]
1343 * See also #sort_by. It implements a Schwartzian transform
1344 * which is useful when key computation or comparison is expensive.
1348 enum_sort(VALUE obj
)
1350 return rb_ary_sort_bang(enum_to_a(0, 0, obj
));
1353 #define SORT_BY_BUFSIZE 16
1354 #define SORT_BY_UNIFORMED(num, flo, fix) (((num&1)<<2)|((flo&1)<<1)|fix)
1355 struct sort_by_data
{
1359 uint8_t primitive_uniformed
;
1363 sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _data
))
1365 struct sort_by_data
*data
= (struct sort_by_data
*)&MEMO_CAST(_data
)->v1
;
1366 VALUE ary
= data
->ary
;
1371 v
= enum_yield(argc
, i
);
1373 if (RBASIC(ary
)->klass
) {
1374 rb_raise(rb_eRuntimeError
, "sort_by reentered");
1376 if (RARRAY_LEN(data
->buf
) != SORT_BY_BUFSIZE
*2) {
1377 rb_raise(rb_eRuntimeError
, "sort_by reentered");
1380 if (data
->primitive_uniformed
) {
1381 data
->primitive_uniformed
&= SORT_BY_UNIFORMED((FIXNUM_P(v
)) || (RB_FLOAT_TYPE_P(v
)),
1385 RARRAY_ASET(data
->buf
, data
->n
*2, v
);
1386 RARRAY_ASET(data
->buf
, data
->n
*2+1, i
);
1388 if (data
->n
== SORT_BY_BUFSIZE
) {
1389 rb_ary_concat(ary
, data
->buf
);
1396 sort_by_cmp(const void *ap
, const void *bp
, void *data
)
1400 VALUE ary
= (VALUE
)data
;
1402 if (RBASIC(ary
)->klass
) {
1403 rb_raise(rb_eRuntimeError
, "sort_by reentered");
1409 return OPTIMIZED_CMP(a
, b
);
1414 This is parts of uniform sort
1417 #define uless rb_uniform_is_less
1418 #define UNIFORM_SWAP(a,b)\
1419 do{struct rb_uniform_sort_data tmp = a; a = b; b = tmp;} while(0)
1421 struct rb_uniform_sort_data
{
1427 rb_uniform_is_less(VALUE a
, VALUE b
)
1430 if (FIXNUM_P(a
) && FIXNUM_P(b
)) {
1431 return (SIGNED_VALUE
)a
< (SIGNED_VALUE
)b
;
1433 else if (FIXNUM_P(a
)) {
1434 RUBY_ASSERT(RB_FLOAT_TYPE_P(b
));
1435 return rb_float_cmp(b
, a
) > 0;
1438 RUBY_ASSERT(RB_FLOAT_TYPE_P(a
));
1439 return rb_float_cmp(a
, b
) < 0;
1444 rb_uniform_is_larger(VALUE a
, VALUE b
)
1447 if (FIXNUM_P(a
) && FIXNUM_P(b
)) {
1448 return (SIGNED_VALUE
)a
> (SIGNED_VALUE
)b
;
1450 else if (FIXNUM_P(a
)) {
1451 RUBY_ASSERT(RB_FLOAT_TYPE_P(b
));
1452 return rb_float_cmp(b
, a
) < 0;
1455 RUBY_ASSERT(RB_FLOAT_TYPE_P(a
));
1456 return rb_float_cmp(a
, b
) > 0;
1460 #define med3_val(a,b,c) (uless(a,b)?(uless(b,c)?b:uless(c,a)?a:c):(uless(c,b)?b:uless(a,c)?a:c))
1463 rb_uniform_insertionsort_2(struct rb_uniform_sort_data
* ptr_begin
,
1464 struct rb_uniform_sort_data
* ptr_end
)
1466 if ((ptr_end
- ptr_begin
) < 2) return;
1467 struct rb_uniform_sort_data tmp
, *j
, *k
,
1468 *index
= ptr_begin
+1;
1469 for (; index
< ptr_end
; index
++) {
1472 if (uless(tmp
.v
, ptr_begin
->v
)) {
1473 while (ptr_begin
< j
) {
1479 while (uless(tmp
.v
, (--k
)->v
)) {
1489 rb_uniform_heap_down_2(struct rb_uniform_sort_data
* ptr_begin
,
1490 size_t offset
, size_t len
)
1493 struct rb_uniform_sort_data tmp
= ptr_begin
[offset
];
1494 while ((c
= (offset
<<1)+1) <= len
) {
1495 if (c
< len
&& uless(ptr_begin
[c
].v
, ptr_begin
[c
+1].v
)) {
1498 if (!uless(tmp
.v
, ptr_begin
[c
].v
)) break;
1499 ptr_begin
[offset
] = ptr_begin
[c
];
1502 ptr_begin
[offset
] = tmp
;
1506 rb_uniform_heapsort_2(struct rb_uniform_sort_data
* ptr_begin
,
1507 struct rb_uniform_sort_data
* ptr_end
)
1509 size_t n
= ptr_end
- ptr_begin
;
1512 for (size_t offset
= n
>>1; offset
> 0;) {
1513 rb_uniform_heap_down_2(ptr_begin
, --offset
, n
-1);
1515 for (size_t offset
= n
-1; offset
> 0;) {
1516 UNIFORM_SWAP(*ptr_begin
, ptr_begin
[offset
]);
1517 rb_uniform_heap_down_2(ptr_begin
, 0, --offset
);
1523 rb_uniform_quicksort_intro_2(struct rb_uniform_sort_data
* ptr_begin
,
1524 struct rb_uniform_sort_data
* ptr_end
, size_t d
)
1527 if (ptr_end
- ptr_begin
<= 16) {
1528 rb_uniform_insertionsort_2(ptr_begin
, ptr_end
);
1532 rb_uniform_heapsort_2(ptr_begin
, ptr_end
);
1536 VALUE x
= med3_val(ptr_begin
->v
,
1537 ptr_begin
[(ptr_end
- ptr_begin
)>>1].v
,
1539 struct rb_uniform_sort_data
*i
= ptr_begin
;
1540 struct rb_uniform_sort_data
*j
= ptr_end
-1;
1543 while (uless(i
->v
, x
)) i
++;
1544 while (uless(x
, j
->v
)) j
--;
1546 UNIFORM_SWAP(*i
, *j
);
1552 if (ptr_end
- j
> 1) rb_uniform_quicksort_intro_2(j
, ptr_end
, d
-1);
1553 if (i
- ptr_begin
> 1) rb_uniform_quicksort_intro_2(ptr_begin
, i
, d
-1);
1557 * Direct primitive data compare sort. Implement with intro sort.
1558 * @param[in] ptr_begin The begin address of target rb_ary's raw pointer.
1559 * @param[in] ptr_end The end address of target rb_ary's raw pointer.
1562 rb_uniform_intro_sort_2(struct rb_uniform_sort_data
* ptr_begin
,
1563 struct rb_uniform_sort_data
* ptr_end
)
1565 size_t n
= ptr_end
- ptr_begin
;
1566 size_t d
= CHAR_BIT
* sizeof(n
) - nlz_intptr(n
) - 1;
1567 bool sorted_flag
= true;
1569 for (struct rb_uniform_sort_data
* ptr
= ptr_begin
+1; ptr
< ptr_end
; ptr
++) {
1570 if (rb_uniform_is_larger((ptr
-1)->v
, (ptr
)->v
)) {
1571 sorted_flag
= false;
1579 rb_uniform_quicksort_intro_2(ptr_begin
, ptr_end
, d
<<1);
1587 * sort_by {|element| ... } -> array
1588 * sort_by -> enumerator
1590 * With a block given, returns an array of elements of +self+,
1591 * sorted according to the value returned by the block for each element.
1592 * The ordering of equal elements is indeterminate and may be unstable.
1596 * a = %w[xx xxx x xxxx]
1597 * a.sort_by {|s| s.size } # => ["x", "xx", "xxx", "xxxx"]
1598 * a.sort_by {|s| -s.size } # => ["xxxx", "xxx", "xx", "x"]
1599 * h = {foo: 2, bar: 1, baz: 0}
1600 * h.sort_by{|key, value| value } # => [[:baz, 0], [:bar, 1], [:foo, 2]]
1601 * h.sort_by{|key, value| key } # => [[:bar, 1], [:baz, 0], [:foo, 2]]
1603 * With no block given, returns an Enumerator.
1605 * The current implementation of #sort_by generates an array of
1606 * tuples containing the original collection element and the mapped
1607 * value. This makes #sort_by fairly expensive when the keysets are
1610 * require 'benchmark'
1612 * a = (1..100000).map { rand(100000) }
1614 * Benchmark.bm(10) do |b|
1615 * b.report("Sort") { a.sort }
1616 * b.report("Sort by") { a.sort_by { |a| a } }
1619 * <em>produces:</em>
1621 * user system total real
1622 * Sort 0.180000 0.000000 0.180000 ( 0.175469)
1623 * Sort by 1.980000 0.040000 2.020000 ( 2.013586)
1625 * However, consider the case where comparing the keys is a non-trivial
1626 * operation. The following code sorts some files on modification time
1627 * using the basic #sort method.
1630 * sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime }
1631 * sorted #=> ["mon", "tues", "wed", "thurs"]
1633 * This sort is inefficient: it generates two new File
1634 * objects during every comparison. A slightly better technique is to
1635 * use the Kernel#test method to generate the modification
1639 * sorted = files.sort { |a, b|
1640 * test(?M, a) <=> test(?M, b)
1642 * sorted #=> ["mon", "tues", "wed", "thurs"]
1644 * This still generates many unnecessary Time objects. A more
1645 * efficient technique is to cache the sort keys (modification times
1646 * in this case) before the sort. Perl users often call this approach
1647 * a Schwartzian transform, after Randal Schwartz. We construct a
1648 * temporary array, where each element is an array containing our
1649 * sort key along with the filename. We sort this array, and then
1650 * extract the filename from the result.
1652 * sorted = Dir["*"].collect { |f|
1654 * }.sort.collect { |f| f[1] }
1655 * sorted #=> ["mon", "tues", "wed", "thurs"]
1657 * This is exactly what #sort_by does internally.
1659 * sorted = Dir["*"].sort_by { |f| test(?M, f) }
1660 * sorted #=> ["mon", "tues", "wed", "thurs"]
1662 * To produce the reverse of a specific order, the following can be used:
1664 * ary.sort_by { ... }.reverse!
1668 enum_sort_by(VALUE obj
)
1673 struct sort_by_data
*data
;
1675 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
1677 if (RB_TYPE_P(obj
, T_ARRAY
) && RARRAY_LEN(obj
) <= LONG_MAX
/2) {
1678 ary
= rb_ary_new2(RARRAY_LEN(obj
)*2);
1683 RBASIC_CLEAR_CLASS(ary
);
1684 buf
= rb_ary_hidden_new(SORT_BY_BUFSIZE
*2);
1685 rb_ary_store(buf
, SORT_BY_BUFSIZE
*2-1, Qnil
);
1686 memo
= MEMO_NEW(0, 0, 0);
1687 data
= (struct sort_by_data
*)&memo
->v1
;
1688 RB_OBJ_WRITE(memo
, &data
->ary
, ary
);
1689 RB_OBJ_WRITE(memo
, &data
->buf
, buf
);
1691 data
->primitive_uniformed
= SORT_BY_UNIFORMED((CMP_OPTIMIZABLE(FLOAT
) && CMP_OPTIMIZABLE(INTEGER
)),
1692 CMP_OPTIMIZABLE(FLOAT
),
1693 CMP_OPTIMIZABLE(INTEGER
));
1694 rb_block_call(obj
, id_each
, 0, 0, sort_by_i
, (VALUE
)memo
);
1698 rb_ary_resize(buf
, data
->n
*2);
1699 rb_ary_concat(ary
, buf
);
1701 if (RARRAY_LEN(ary
) > 2) {
1702 if (data
->primitive_uniformed
) {
1703 RARRAY_PTR_USE(ary
, ptr
,
1704 rb_uniform_intro_sort_2((struct rb_uniform_sort_data
*)ptr
,
1705 (struct rb_uniform_sort_data
*)(ptr
+ RARRAY_LEN(ary
))));
1708 RARRAY_PTR_USE(ary
, ptr
,
1709 ruby_qsort(ptr
, RARRAY_LEN(ary
)/2, 2*sizeof(VALUE
),
1710 sort_by_cmp
, (void *)ary
));
1713 if (RBASIC(ary
)->klass
) {
1714 rb_raise(rb_eRuntimeError
, "sort_by reentered");
1716 for (i
=1; i
<RARRAY_LEN(ary
); i
+=2) {
1717 RARRAY_ASET(ary
, i
/2, RARRAY_AREF(ary
, i
));
1719 rb_ary_resize(ary
, RARRAY_LEN(ary
)/2);
1720 RBASIC_SET_CLASS_RAW(ary
, rb_cArray
);
1725 #define ENUMFUNC(name) argc ? name##_eqq : rb_block_given_p() ? name##_iter_i : name##_i
1727 #define MEMO_ENUM_NEW(v1) (rb_check_arity(argc, 0, 1), MEMO_NEW((v1), (argc ? *argv : 0), 0))
1729 #define DEFINE_ENUMFUNCS(name) \
1730 static VALUE enum_##name##_func(VALUE result, struct MEMO *memo); \
1733 name##_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1735 return enum_##name##_func(rb_enum_values_pack(argc, argv), MEMO_CAST(memo)); \
1739 name##_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1741 return enum_##name##_func(rb_yield_values2(argc, argv), MEMO_CAST(memo)); \
1745 name##_eqq(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
1747 ENUM_WANT_SVALUE(); \
1748 return enum_##name##_func(rb_funcallv(MEMO_CAST(memo)->v2, id_eqq, 1, &i), MEMO_CAST(memo)); \
1752 enum_##name##_func(VALUE result, struct MEMO *memo)
1754 #define WARN_UNUSED_BLOCK(argc) do { \
1755 if ((argc) > 0 && rb_block_given_p()) { \
1756 rb_warn("given block not used"); \
1760 DEFINE_ENUMFUNCS(all
)
1762 if (!RTEST(result
)) {
1763 MEMO_V1_SET(memo
, Qfalse
);
1771 * all? -> true or false
1772 * all?(pattern) -> true or false
1773 * all? {|element| ... } -> true or false
1775 * Returns whether every element meets a given criterion.
1777 * If +self+ has no element, returns +true+ and argument or block
1780 * With no argument and no block,
1781 * returns whether every element is truthy:
1783 * (1..4).all? # => true
1784 * %w[a b c d].all? # => true
1785 * [1, 2, nil].all? # => false
1786 * ['a','b', false].all? # => false
1789 * With argument +pattern+ and no block,
1790 * returns whether for each element +element+,
1791 * <tt>pattern === element</tt>:
1793 * (1..4).all?(Integer) # => true
1794 * (1..4).all?(Numeric) # => true
1795 * (1..4).all?(Float) # => false
1796 * %w[bar baz bat bam].all?(/ba/) # => true
1797 * %w[bar baz bat bam].all?(/bar/) # => false
1798 * %w[bar baz bat bam].all?('ba') # => false
1799 * {foo: 0, bar: 1, baz: 2}.all?(Array) # => true
1800 * {foo: 0, bar: 1, baz: 2}.all?(Hash) # => false
1801 * [].all?(Integer) # => true
1803 * With a block given, returns whether the block returns a truthy value
1804 * for every element:
1806 * (1..4).all? {|element| element < 5 } # => true
1807 * (1..4).all? {|element| element < 4 } # => false
1808 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 3 } # => true
1809 * {foo: 0, bar: 1, baz: 2}.all? {|key, value| value < 2 } # => false
1811 * Related: #any?, #none? #one?.
1816 enum_all(int argc
, VALUE
*argv
, VALUE obj
)
1818 struct MEMO
*memo
= MEMO_ENUM_NEW(Qtrue
);
1819 WARN_UNUSED_BLOCK(argc
);
1820 rb_block_call(obj
, id_each
, 0, 0, ENUMFUNC(all
), (VALUE
)memo
);
1824 DEFINE_ENUMFUNCS(any
)
1826 if (RTEST(result
)) {
1827 MEMO_V1_SET(memo
, Qtrue
);
1835 * any? -> true or false
1836 * any?(pattern) -> true or false
1837 * any? {|element| ... } -> true or false
1839 * Returns whether any element meets a given criterion.
1841 * If +self+ has no element, returns +false+ and argument or block
1844 * With no argument and no block,
1845 * returns whether any element is truthy:
1847 * (1..4).any? # => true
1848 * %w[a b c d].any? # => true
1849 * [1, false, nil].any? # => true
1850 * [].any? # => false
1852 * With argument +pattern+ and no block,
1853 * returns whether for any element +element+,
1854 * <tt>pattern === element</tt>:
1856 * [nil, false, 0].any?(Integer) # => true
1857 * [nil, false, 0].any?(Numeric) # => true
1858 * [nil, false, 0].any?(Float) # => false
1859 * %w[bar baz bat bam].any?(/m/) # => true
1860 * %w[bar baz bat bam].any?(/foo/) # => false
1861 * %w[bar baz bat bam].any?('ba') # => false
1862 * {foo: 0, bar: 1, baz: 2}.any?(Array) # => true
1863 * {foo: 0, bar: 1, baz: 2}.any?(Hash) # => false
1864 * [].any?(Integer) # => false
1866 * With a block given, returns whether the block returns a truthy value
1869 * (1..4).any? {|element| element < 2 } # => true
1870 * (1..4).any? {|element| element < 1 } # => false
1871 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 1 } # => true
1872 * {foo: 0, bar: 1, baz: 2}.any? {|key, value| value < 0 } # => false
1874 * Related: #all?, #none?, #one?.
1878 enum_any(int argc
, VALUE
*argv
, VALUE obj
)
1880 struct MEMO
*memo
= MEMO_ENUM_NEW(Qfalse
);
1881 WARN_UNUSED_BLOCK(argc
);
1882 rb_block_call(obj
, id_each
, 0, 0, ENUMFUNC(any
), (VALUE
)memo
);
1886 DEFINE_ENUMFUNCS(one
)
1888 if (RTEST(result
)) {
1889 if (UNDEF_P(memo
->v1
)) {
1890 MEMO_V1_SET(memo
, Qtrue
);
1892 else if (memo
->v1
== Qtrue
) {
1893 MEMO_V1_SET(memo
, Qfalse
);
1906 int (*cmpfunc
)(const void *, const void *, void *);
1907 int rev
: 1; /* max if 1 */
1908 int by
: 1; /* min_by if 1 */
1912 cmpint_reenter_check(struct nmin_data
*data
, VALUE val
)
1914 if (RBASIC(data
->buf
)->klass
) {
1915 rb_raise(rb_eRuntimeError
, "%s%s reentered",
1916 data
->rev
? "max" : "min",
1917 data
->by
? "_by" : "");
1923 nmin_cmp(const void *ap
, const void *bp
, void *_data
)
1925 struct nmin_data
*data
= (struct nmin_data
*)_data
;
1926 VALUE a
= *(const VALUE
*)ap
, b
= *(const VALUE
*)bp
;
1927 #define rb_cmpint(cmp, a, b) rb_cmpint(cmpint_reenter_check(data, (cmp)), a, b)
1928 return OPTIMIZED_CMP(a
, b
);
1933 nmin_block_cmp(const void *ap
, const void *bp
, void *_data
)
1935 struct nmin_data
*data
= (struct nmin_data
*)_data
;
1936 VALUE a
= *(const VALUE
*)ap
, b
= *(const VALUE
*)bp
;
1937 VALUE cmp
= rb_yield_values(2, a
, b
);
1938 cmpint_reenter_check(data
, cmp
);
1939 return rb_cmpint(cmp
, a
, b
);
1943 nmin_filter(struct nmin_data
*data
)
1955 if (data
->curlen
<= data
->n
)
1959 beg
= RARRAY_PTR(data
->buf
);
1960 eltsize
= data
->by
? 2 : 1;
1961 numelts
= data
->curlen
;
1966 #define GETPTR(i) (beg+(i)*eltsize)
1968 #define SWAP(i, j) do { \
1970 memcpy(tmp, GETPTR(i), sizeof(VALUE)*eltsize); \
1971 memcpy(GETPTR(i), GETPTR(j), sizeof(VALUE)*eltsize); \
1972 memcpy(GETPTR(j), tmp, sizeof(VALUE)*eltsize); \
1976 long pivot_index
= left
+ (right
-left
)/2;
1977 long num_pivots
= 1;
1979 SWAP(pivot_index
, right
);
1980 pivot_index
= right
;
1984 while (i
<= right
-num_pivots
) {
1985 int c
= data
->cmpfunc(GETPTR(i
), GETPTR(pivot_index
), data
);
1989 SWAP(i
, right
-num_pivots
);
1994 SWAP(i
, store_index
);
2000 for (i
= right
; right
-num_pivots
< i
; i
--) {
2007 if (store_index
<= n
&& n
<= store_index
+num_pivots
)
2010 if (n
< store_index
) {
2011 right
= store_index
-1;
2014 left
= store_index
+num_pivots
;
2020 data
->limit
= RARRAY_AREF(data
->buf
, store_index
*eltsize
); /* the last pivot */
2021 data
->curlen
= data
->n
;
2022 rb_ary_resize(data
->buf
, data
->n
* eltsize
);
2026 nmin_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _data
))
2028 struct nmin_data
*data
= (struct nmin_data
*)_data
;
2034 cmpv
= enum_yield(argc
, i
);
2038 if (!UNDEF_P(data
->limit
)) {
2039 int c
= data
->cmpfunc(&cmpv
, &data
->limit
, data
);
2047 rb_ary_push(data
->buf
, cmpv
);
2048 rb_ary_push(data
->buf
, i
);
2052 if (data
->curlen
== data
->bufmax
) {
2060 rb_nmin_run(VALUE obj
, VALUE num
, int by
, int rev
, int ary
)
2063 struct nmin_data data
;
2065 data
.n
= NUM2LONG(num
);
2067 rb_raise(rb_eArgError
, "negative size (%ld)", data
.n
);
2069 return rb_ary_new2(0);
2070 if (LONG_MAX
/4/(by
? 2 : 1) < data
.n
)
2071 rb_raise(rb_eArgError
, "too big size");
2072 data
.bufmax
= data
.n
* 4;
2074 data
.buf
= rb_ary_hidden_new(data
.bufmax
* (by
? 2 : 1));
2075 data
.limit
= Qundef
;
2076 data
.cmpfunc
= by
? nmin_cmp
:
2077 rb_block_given_p() ? nmin_block_cmp
:
2083 for (i
= 0; i
< RARRAY_LEN(obj
); i
++) {
2085 args
[0] = RARRAY_AREF(obj
, i
);
2086 nmin_i(obj
, (VALUE
)&data
, 1, args
, Qundef
);
2090 rb_block_call(obj
, id_each
, 0, 0, nmin_i
, (VALUE
)&data
);
2096 RARRAY_PTR_USE(result
, ptr
, {
2098 RARRAY_LEN(result
)/2,
2100 data
.cmpfunc
, (void *)&data
);
2101 for (i
=1; i
<RARRAY_LEN(result
); i
+=2) {
2105 rb_ary_resize(result
, RARRAY_LEN(result
)/2);
2108 RARRAY_PTR_USE(result
, ptr
, {
2109 ruby_qsort(ptr
, RARRAY_LEN(result
), sizeof(VALUE
),
2110 data
.cmpfunc
, (void *)&data
);
2114 rb_ary_reverse(result
);
2116 RBASIC_SET_CLASS(result
, rb_cArray
);
2123 * one? -> true or false
2124 * one?(pattern) -> true or false
2125 * one? {|element| ... } -> true or false
2127 * Returns whether exactly one element meets a given criterion.
2129 * With no argument and no block,
2130 * returns whether exactly one element is truthy:
2132 * (1..1).one? # => true
2133 * [1, nil, false].one? # => true
2134 * (1..4).one? # => false
2135 * {foo: 0}.one? # => true
2136 * {foo: 0, bar: 1}.one? # => false
2137 * [].one? # => false
2139 * With argument +pattern+ and no block,
2140 * returns whether for exactly one element +element+,
2141 * <tt>pattern === element</tt>:
2143 * [nil, false, 0].one?(Integer) # => true
2144 * [nil, false, 0].one?(Numeric) # => true
2145 * [nil, false, 0].one?(Float) # => false
2146 * %w[bar baz bat bam].one?(/m/) # => true
2147 * %w[bar baz bat bam].one?(/foo/) # => false
2148 * %w[bar baz bat bam].one?('ba') # => false
2149 * {foo: 0, bar: 1, baz: 2}.one?(Array) # => false
2150 * {foo: 0}.one?(Array) # => true
2151 * [].one?(Integer) # => false
2153 * With a block given, returns whether the block returns a truthy value
2154 * for exactly one element:
2156 * (1..4).one? {|element| element < 2 } # => true
2157 * (1..4).one? {|element| element < 1 } # => false
2158 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true
2159 * {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
2161 * Related: #none?, #all?, #any?.
2165 enum_one(int argc
, VALUE
*argv
, VALUE obj
)
2167 struct MEMO
*memo
= MEMO_ENUM_NEW(Qundef
);
2170 WARN_UNUSED_BLOCK(argc
);
2171 rb_block_call(obj
, id_each
, 0, 0, ENUMFUNC(one
), (VALUE
)memo
);
2173 if (UNDEF_P(result
)) return Qfalse
;
2177 DEFINE_ENUMFUNCS(none
)
2179 if (RTEST(result
)) {
2180 MEMO_V1_SET(memo
, Qfalse
);
2188 * none? -> true or false
2189 * none?(pattern) -> true or false
2190 * none? {|element| ... } -> true or false
2192 * Returns whether no element meets a given criterion.
2194 * With no argument and no block,
2195 * returns whether no element is truthy:
2197 * (1..4).none? # => false
2198 * [nil, false].none? # => true
2199 * {foo: 0}.none? # => false
2200 * {foo: 0, bar: 1}.none? # => false
2201 * [].none? # => true
2203 * With argument +pattern+ and no block,
2204 * returns whether for no element +element+,
2205 * <tt>pattern === element</tt>:
2207 * [nil, false, 1.1].none?(Integer) # => true
2208 * %w[bar baz bat bam].none?(/m/) # => false
2209 * %w[bar baz bat bam].none?(/foo/) # => true
2210 * %w[bar baz bat bam].none?('ba') # => true
2211 * {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true
2212 * {foo: 0}.none?(Array) # => false
2213 * [].none?(Integer) # => true
2215 * With a block given, returns whether the block returns a truthy value
2218 * (1..4).none? {|element| element < 1 } # => true
2219 * (1..4).none? {|element| element < 2 } # => false
2220 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true
2221 * {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
2223 * Related: #one?, #all?, #any?.
2227 enum_none(int argc
, VALUE
*argv
, VALUE obj
)
2229 struct MEMO
*memo
= MEMO_ENUM_NEW(Qtrue
);
2231 WARN_UNUSED_BLOCK(argc
);
2232 rb_block_call(obj
, id_each
, 0, 0, ENUMFUNC(none
), (VALUE
)memo
);
2241 min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2243 struct min_t
*memo
= MEMO_FOR(struct min_t
, args
);
2247 if (UNDEF_P(memo
->min
)) {
2251 if (OPTIMIZED_CMP(i
, memo
->min
) < 0) {
2259 min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2262 struct min_t
*memo
= MEMO_FOR(struct min_t
, args
);
2266 if (UNDEF_P(memo
->min
)) {
2270 cmp
= rb_yield_values(2, i
, memo
->min
);
2271 if (rb_cmpint(cmp
, i
, memo
->min
) < 0) {
2283 * min {|a, b| ... } -> element
2284 * min(n) {|a, b| ... } -> array
2286 * Returns the element with the minimum element according to a given criterion.
2287 * The ordering of equal elements is indeterminate and may be unstable.
2289 * With no argument and no block, returns the minimum element,
2290 * using the elements' own method <tt><=></tt> for comparison:
2293 * (-4..-1).min # => -4
2294 * %w[d c b a].min # => "a"
2295 * {foo: 0, bar: 1, baz: 2}.min # => [:bar, 1]
2298 * With positive integer argument +n+ given, and no block,
2299 * returns an array containing the first +n+ minimum elements that exist:
2301 * (1..4).min(2) # => [1, 2]
2302 * (-4..-1).min(2) # => [-4, -3]
2303 * %w[d c b a].min(2) # => ["a", "b"]
2304 * {foo: 0, bar: 1, baz: 2}.min(2) # => [[:bar, 1], [:baz, 2]]
2307 * With a block given, the block determines the minimum elements.
2308 * The block is called with two elements +a+ and +b+, and must return:
2310 * - A negative integer if <tt>a < b</tt>.
2311 * - Zero if <tt>a == b</tt>.
2312 * - A positive integer if <tt>a > b</tt>.
2314 * With a block given and no argument,
2315 * returns the minimum element as determined by the block:
2317 * %w[xxx x xxxx xx].min {|a, b| a.size <=> b.size } # => "x"
2318 * h = {foo: 0, bar: 1, baz: 2}
2319 * h.min {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:foo, 0]
2320 * [].min {|a, b| a <=> b } # => nil
2322 * With a block given and positive integer argument +n+ given,
2323 * returns an array containing the first +n+ minimum elements that exist,
2324 * as determined by the block.
2326 * %w[xxx x xxxx xx].min(2) {|a, b| a.size <=> b.size } # => ["x", "xx"]
2327 * h = {foo: 0, bar: 1, baz: 2}
2328 * h.min(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2329 * # => [[:foo, 0], [:bar, 1]]
2330 * [].min(2) {|a, b| a <=> b } # => []
2332 * Related: #min_by, #minmax, #max.
2337 enum_min(int argc
, VALUE
*argv
, VALUE obj
)
2340 struct min_t
*m
= NEW_MEMO_FOR(struct min_t
, memo
);
2344 if (rb_check_arity(argc
, 0, 1) && !NIL_P(num
= argv
[0]))
2345 return rb_nmin_run(obj
, num
, 0, 0, 0);
2348 if (rb_block_given_p()) {
2349 rb_block_call(obj
, id_each
, 0, 0, min_ii
, memo
);
2352 rb_block_call(obj
, id_each
, 0, 0, min_i
, memo
);
2355 if (UNDEF_P(result
)) return Qnil
;
2364 max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2366 struct max_t
*memo
= MEMO_FOR(struct max_t
, args
);
2370 if (UNDEF_P(memo
->max
)) {
2374 if (OPTIMIZED_CMP(i
, memo
->max
) > 0) {
2382 max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2384 struct max_t
*memo
= MEMO_FOR(struct max_t
, args
);
2389 if (UNDEF_P(memo
->max
)) {
2393 cmp
= rb_yield_values(2, i
, memo
->max
);
2394 if (rb_cmpint(cmp
, i
, memo
->max
) > 0) {
2405 * max {|a, b| ... } -> element
2406 * max(n) {|a, b| ... } -> array
2408 * Returns the element with the maximum element according to a given criterion.
2409 * The ordering of equal elements is indeterminate and may be unstable.
2411 * With no argument and no block, returns the maximum element,
2412 * using the elements' own method <tt><=></tt> for comparison:
2415 * (-4..-1).max # => -1
2416 * %w[d c b a].max # => "d"
2417 * {foo: 0, bar: 1, baz: 2}.max # => [:foo, 0]
2420 * With positive integer argument +n+ given, and no block,
2421 * returns an array containing the first +n+ maximum elements that exist:
2423 * (1..4).max(2) # => [4, 3]
2424 * (-4..-1).max(2) # => [-1, -2]
2425 * %w[d c b a].max(2) # => ["d", "c"]
2426 * {foo: 0, bar: 1, baz: 2}.max(2) # => [[:foo, 0], [:baz, 2]]
2429 * With a block given, the block determines the maximum elements.
2430 * The block is called with two elements +a+ and +b+, and must return:
2432 * - A negative integer if <tt>a < b</tt>.
2433 * - Zero if <tt>a == b</tt>.
2434 * - A positive integer if <tt>a > b</tt>.
2436 * With a block given and no argument,
2437 * returns the maximum element as determined by the block:
2439 * %w[xxx x xxxx xx].max {|a, b| a.size <=> b.size } # => "xxxx"
2440 * h = {foo: 0, bar: 1, baz: 2}
2441 * h.max {|pair1, pair2| pair1[1] <=> pair2[1] } # => [:baz, 2]
2442 * [].max {|a, b| a <=> b } # => nil
2444 * With a block given and positive integer argument +n+ given,
2445 * returns an array containing the first +n+ maximum elements that exist,
2446 * as determined by the block.
2448 * %w[xxx x xxxx xx].max(2) {|a, b| a.size <=> b.size } # => ["xxxx", "xxx"]
2449 * h = {foo: 0, bar: 1, baz: 2}
2450 * h.max(2) {|pair1, pair2| pair1[1] <=> pair2[1] }
2451 * # => [[:baz, 2], [:bar, 1]]
2452 * [].max(2) {|a, b| a <=> b } # => []
2454 * Related: #min, #minmax, #max_by.
2459 enum_max(int argc
, VALUE
*argv
, VALUE obj
)
2462 struct max_t
*m
= NEW_MEMO_FOR(struct max_t
, memo
);
2466 if (rb_check_arity(argc
, 0, 1) && !NIL_P(num
= argv
[0]))
2467 return rb_nmin_run(obj
, num
, 0, 1, 0);
2470 if (rb_block_given_p()) {
2471 rb_block_call(obj
, id_each
, 0, 0, max_ii
, (VALUE
)memo
);
2474 rb_block_call(obj
, id_each
, 0, 0, max_i
, (VALUE
)memo
);
2477 if (UNDEF_P(result
)) return Qnil
;
2488 minmax_i_update(VALUE i
, VALUE j
, struct minmax_t
*memo
)
2492 if (UNDEF_P(memo
->min
)) {
2497 n
= OPTIMIZED_CMP(i
, memo
->min
);
2501 n
= OPTIMIZED_CMP(j
, memo
->max
);
2509 minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
2511 struct minmax_t
*memo
= MEMO_FOR(struct minmax_t
, _memo
);
2517 if (UNDEF_P(memo
->last
)) {
2522 memo
->last
= Qundef
;
2524 n
= OPTIMIZED_CMP(j
, i
);
2534 minmax_i_update(i
, j
, memo
);
2540 minmax_ii_update(VALUE i
, VALUE j
, struct minmax_t
*memo
)
2544 if (UNDEF_P(memo
->min
)) {
2549 n
= rb_cmpint(rb_yield_values(2, i
, memo
->min
), i
, memo
->min
);
2553 n
= rb_cmpint(rb_yield_values(2, j
, memo
->max
), j
, memo
->max
);
2561 minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
2563 struct minmax_t
*memo
= MEMO_FOR(struct minmax_t
, _memo
);
2569 if (UNDEF_P(memo
->last
)) {
2574 memo
->last
= Qundef
;
2576 n
= rb_cmpint(rb_yield_values(2, j
, i
), j
, i
);
2586 minmax_ii_update(i
, j
, memo
);
2593 * minmax -> [minimum, maximum]
2594 * minmax {|a, b| ... } -> [minimum, maximum]
2596 * Returns a 2-element array containing the minimum and maximum elements
2597 * according to a given criterion.
2598 * The ordering of equal elements is indeterminate and may be unstable.
2600 * With no argument and no block, returns the minimum and maximum elements,
2601 * using the elements' own method <tt><=></tt> for comparison:
2603 * (1..4).minmax # => [1, 4]
2604 * (-4..-1).minmax # => [-4, -1]
2605 * %w[d c b a].minmax # => ["a", "d"]
2606 * {foo: 0, bar: 1, baz: 2}.minmax # => [[:bar, 1], [:foo, 0]]
2607 * [].minmax # => [nil, nil]
2609 * With a block given, returns the minimum and maximum elements
2610 * as determined by the block:
2612 * %w[xxx x xxxx xx].minmax {|a, b| a.size <=> b.size } # => ["x", "xxxx"]
2613 * h = {foo: 0, bar: 1, baz: 2}
2614 * h.minmax {|pair1, pair2| pair1[1] <=> pair2[1] }
2615 * # => [[:foo, 0], [:baz, 2]]
2616 * [].minmax {|a, b| a <=> b } # => [nil, nil]
2618 * Related: #min, #max, #minmax_by.
2623 enum_minmax(VALUE obj
)
2626 struct minmax_t
*m
= NEW_MEMO_FOR(struct minmax_t
, memo
);
2630 if (rb_block_given_p()) {
2631 rb_block_call(obj
, id_each
, 0, 0, minmax_ii
, memo
);
2632 if (!UNDEF_P(m
->last
))
2633 minmax_ii_update(m
->last
, m
->last
, m
);
2636 rb_block_call(obj
, id_each
, 0, 0, minmax_i
, memo
);
2637 if (!UNDEF_P(m
->last
))
2638 minmax_i_update(m
->last
, m
->last
, m
);
2640 if (!UNDEF_P(m
->min
)) {
2641 return rb_assoc_new(m
->min
, m
->max
);
2643 return rb_assoc_new(Qnil
, Qnil
);
2647 min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2649 struct MEMO
*memo
= MEMO_CAST(args
);
2654 v
= enum_yield(argc
, i
);
2655 if (UNDEF_P(memo
->v1
)) {
2656 MEMO_V1_SET(memo
, v
);
2657 MEMO_V2_SET(memo
, i
);
2659 else if (OPTIMIZED_CMP(v
, memo
->v1
) < 0) {
2660 MEMO_V1_SET(memo
, v
);
2661 MEMO_V2_SET(memo
, i
);
2668 * min_by {|element| ... } -> element
2669 * min_by(n) {|element| ... } -> array
2670 * min_by -> enumerator
2671 * min_by(n) -> enumerator
2673 * Returns the elements for which the block returns the minimum values.
2675 * With a block given and no argument,
2676 * returns the element for which the block returns the minimum value:
2678 * (1..4).min_by {|element| -element } # => 4
2679 * %w[a b c d].min_by {|element| -element.ord } # => "d"
2680 * {foo: 0, bar: 1, baz: 2}.min_by {|key, value| -value } # => [:baz, 2]
2681 * [].min_by {|element| -element } # => nil
2683 * With a block given and positive integer argument +n+ given,
2684 * returns an array containing the +n+ elements
2685 * for which the block returns minimum values:
2687 * (1..4).min_by(2) {|element| -element }
2689 * %w[a b c d].min_by(2) {|element| -element.ord }
2691 * {foo: 0, bar: 1, baz: 2}.min_by(2) {|key, value| -value }
2692 * # => [[:baz, 2], [:bar, 1]]
2693 * [].min_by(2) {|element| -element }
2696 * Returns an Enumerator if no block is given.
2698 * Related: #min, #minmax, #max_by.
2703 enum_min_by(int argc
, VALUE
*argv
, VALUE obj
)
2708 rb_check_arity(argc
, 0, 1);
2710 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
2712 if (argc
&& !NIL_P(num
= argv
[0]))
2713 return rb_nmin_run(obj
, num
, 1, 0, 0);
2715 memo
= MEMO_NEW(Qundef
, Qnil
, 0);
2716 rb_block_call(obj
, id_each
, 0, 0, min_by_i
, (VALUE
)memo
);
2721 max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
2723 struct MEMO
*memo
= MEMO_CAST(args
);
2728 v
= enum_yield(argc
, i
);
2729 if (UNDEF_P(memo
->v1
)) {
2730 MEMO_V1_SET(memo
, v
);
2731 MEMO_V2_SET(memo
, i
);
2733 else if (OPTIMIZED_CMP(v
, memo
->v1
) > 0) {
2734 MEMO_V1_SET(memo
, v
);
2735 MEMO_V2_SET(memo
, i
);
2742 * max_by {|element| ... } -> element
2743 * max_by(n) {|element| ... } -> array
2744 * max_by -> enumerator
2745 * max_by(n) -> enumerator
2747 * Returns the elements for which the block returns the maximum values.
2749 * With a block given and no argument,
2750 * returns the element for which the block returns the maximum value:
2752 * (1..4).max_by {|element| -element } # => 1
2753 * %w[a b c d].max_by {|element| -element.ord } # => "a"
2754 * {foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
2755 * [].max_by {|element| -element } # => nil
2757 * With a block given and positive integer argument +n+ given,
2758 * returns an array containing the +n+ elements
2759 * for which the block returns maximum values:
2761 * (1..4).max_by(2) {|element| -element }
2763 * %w[a b c d].max_by(2) {|element| -element.ord }
2765 * {foo: 0, bar: 1, baz: 2}.max_by(2) {|key, value| -value }
2766 * # => [[:foo, 0], [:bar, 1]]
2767 * [].max_by(2) {|element| -element }
2770 * Returns an Enumerator if no block is given.
2772 * Related: #max, #minmax, #min_by.
2777 enum_max_by(int argc
, VALUE
*argv
, VALUE obj
)
2782 rb_check_arity(argc
, 0, 1);
2784 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
2786 if (argc
&& !NIL_P(num
= argv
[0]))
2787 return rb_nmin_run(obj
, num
, 1, 1, 0);
2789 memo
= MEMO_NEW(Qundef
, Qnil
, 0);
2790 rb_block_call(obj
, id_each
, 0, 0, max_by_i
, (VALUE
)memo
);
2794 struct minmax_by_t
{
2804 minmax_by_i_update(VALUE v1
, VALUE v2
, VALUE i1
, VALUE i2
, struct minmax_by_t
*memo
)
2806 if (UNDEF_P(memo
->min_bv
)) {
2813 if (OPTIMIZED_CMP(v1
, memo
->min_bv
) < 0) {
2817 if (OPTIMIZED_CMP(v2
, memo
->max_bv
) > 0) {
2825 minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
2827 struct minmax_by_t
*memo
= MEMO_FOR(struct minmax_by_t
, _memo
);
2833 vi
= enum_yield(argc
, i
);
2835 if (UNDEF_P(memo
->last_bv
)) {
2842 memo
->last_bv
= Qundef
;
2844 n
= OPTIMIZED_CMP(vj
, vi
);
2859 minmax_by_i_update(vi
, vj
, i
, j
, memo
);
2866 * minmax_by {|element| ... } -> [minimum, maximum]
2867 * minmax_by -> enumerator
2869 * Returns a 2-element array containing the elements
2870 * for which the block returns minimum and maximum values:
2872 * (1..4).minmax_by {|element| -element }
2874 * %w[a b c d].minmax_by {|element| -element.ord }
2876 * {foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
2877 * # => [[:baz, 2], [:foo, 0]]
2878 * [].minmax_by {|element| -element }
2881 * Returns an Enumerator if no block is given.
2883 * Related: #max_by, #minmax, #min_by.
2888 enum_minmax_by(VALUE obj
)
2891 struct minmax_by_t
*m
= NEW_MEMO_FOR(struct minmax_by_t
, memo
);
2893 RETURN_SIZED_ENUMERATOR(obj
, 0, 0, enum_size
);
2899 m
->last_bv
= Qundef
;
2901 rb_block_call(obj
, id_each
, 0, 0, minmax_by_i
, memo
);
2902 if (!UNDEF_P(m
->last_bv
))
2903 minmax_by_i_update(m
->last_bv
, m
->last_bv
, m
->last
, m
->last
, m
);
2904 m
= MEMO_FOR(struct minmax_by_t
, memo
);
2905 return rb_assoc_new(m
->min
, m
->max
);
2909 member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter
, args
))
2911 struct MEMO
*memo
= MEMO_CAST(args
);
2913 if (rb_equal(rb_enum_values_pack(argc
, argv
), memo
->v1
)) {
2914 MEMO_V2_SET(memo
, Qtrue
);
2922 * include?(object) -> true or false
2924 * Returns whether for any element <tt>object == element</tt>:
2926 * (1..4).include?(2) # => true
2927 * (1..4).include?(5) # => false
2928 * (1..4).include?('2') # => false
2929 * %w[a b c d].include?('b') # => true
2930 * %w[a b c d].include?('2') # => false
2931 * {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true
2932 * {foo: 0, bar: 1, baz: 2}.include?('foo') # => false
2933 * {foo: 0, bar: 1, baz: 2}.include?(0) # => false
2938 enum_member(VALUE obj
, VALUE val
)
2940 struct MEMO
*memo
= MEMO_NEW(val
, Qfalse
, 0);
2942 rb_block_call(obj
, id_each
, 0, 0, member_i
, (VALUE
)memo
);
2947 each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memo
))
2949 struct MEMO
*m
= MEMO_CAST(memo
);
2950 VALUE n
= imemo_count_value(m
);
2953 return rb_yield_values(2, rb_enum_values_pack(argc
, argv
), n
);
2958 * each_with_index(*args) {|element, i| ..... } -> self
2959 * each_with_index(*args) -> enumerator
2961 * With a block given, calls the block with each element and its index;
2965 * (1..4).each_with_index {|element, i| h[element] = i } # => 1..4
2966 * h # => {1=>0, 2=>1, 3=>2, 4=>3}
2969 * %w[a b c d].each_with_index {|element, i| h[element] = i }
2970 * # => ["a", "b", "c", "d"]
2971 * h # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3}
2974 * h = {foo: 0, bar: 1, baz: 2}
2975 * h.each_with_index {|element, i| a.push([i, element]) }
2976 * # => {:foo=>0, :bar=>1, :baz=>2}
2977 * a # => [[0, [:foo, 0]], [1, [:bar, 1]], [2, [:baz, 2]]]
2979 * With no block given, returns an Enumerator.
2984 enum_each_with_index(int argc
, VALUE
*argv
, VALUE obj
)
2988 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
2990 memo
= MEMO_NEW(0, 0, 0);
2991 rb_block_call(obj
, id_each
, argc
, argv
, each_with_index_i
, (VALUE
)memo
);
2998 * reverse_each(*args) {|element| ... } -> self
2999 * reverse_each(*args) -> enumerator
3001 * With a block given, calls the block with each element,
3002 * but in reverse order; returns +self+:
3005 * (1..4).reverse_each {|element| a.push(-element) } # => 1..4
3006 * a # => [-4, -3, -2, -1]
3009 * %w[a b c d].reverse_each {|element| a.push(element) }
3010 * # => ["a", "b", "c", "d"]
3011 * a # => ["d", "c", "b", "a"]
3014 * h.reverse_each {|element| a.push(element) }
3015 * # => {:foo=>0, :bar=>1, :baz=>2}
3016 * a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
3018 * With no block given, returns an Enumerator.
3023 enum_reverse_each(int argc
, VALUE
*argv
, VALUE obj
)
3028 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
3030 ary
= enum_to_a(argc
, argv
, obj
);
3032 len
= RARRAY_LEN(ary
);
3035 rb_yield(RARRAY_AREF(ary
, len
));
3036 nlen
= RARRAY_LEN(ary
);
3047 each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, p
))
3050 enum_yield(argc
, i
);
3056 * each_entry(*args) {|element| ... } -> self
3057 * each_entry(*args) -> enumerator
3059 * Calls the given block with each element,
3060 * converting multiple values from yield to an array; returns +self+:
3063 * (1..4).each_entry {|element| a.push(element) } # => 1..4
3064 * a # => [1, 2, 3, 4]
3067 * h = {foo: 0, bar: 1, baz:2}
3068 * h.each_entry {|element| a.push(element) }
3069 * # => {:foo=>0, :bar=>1, :baz=>2}
3070 * a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3073 * include Enumerable
3080 * Foo.new.each_entry {|yielded| p yielded }
3088 * With no block given, returns an Enumerator.
3093 enum_each_entry(int argc
, VALUE
*argv
, VALUE obj
)
3095 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_size
);
3096 rb_block_call(obj
, id_each
, argc
, argv
, each_val_i
, 0);
3101 add_int(VALUE x
, long n
)
3103 const VALUE y
= LONG2NUM(n
);
3104 if (RB_INTEGER_TYPE_P(x
)) return rb_int_plus(x
, y
);
3105 return rb_funcallv(x
, '+', 1, &y
);
3109 div_int(VALUE x
, long n
)
3111 const VALUE y
= LONG2NUM(n
);
3112 if (RB_INTEGER_TYPE_P(x
)) return rb_int_idiv(x
, y
);
3113 return rb_funcallv(x
, id_div
, 1, &y
);
3116 #define dont_recycle_block_arg(arity) ((arity) == 1 || (arity) < 0)
3119 each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, m
))
3121 struct MEMO
*memo
= MEMO_CAST(m
);
3122 VALUE ary
= memo
->v1
;
3124 long size
= memo
->u3
.cnt
;
3127 rb_ary_push(ary
, i
);
3129 if (RARRAY_LEN(ary
) == size
) {
3133 MEMO_V1_SET(memo
, rb_ary_new2(size
));
3144 enum_each_slice_size(VALUE obj
, VALUE args
, VALUE eobj
)
3147 long slice_size
= NUM2LONG(RARRAY_AREF(args
, 0));
3149 CONST_ID(infinite_p
, "infinite?");
3150 if (slice_size
<= 0) rb_raise(rb_eArgError
, "invalid slice size");
3152 size
= enum_size(obj
, 0, 0);
3153 if (NIL_P(size
)) return Qnil
;
3154 if (RB_FLOAT_TYPE_P(size
) && RTEST(rb_funcall(size
, infinite_p
, 0))) {
3158 n
= add_int(size
, slice_size
-1);
3159 return div_int(n
, slice_size
);
3164 * each_slice(n) { ... } -> self
3165 * each_slice(n) -> enumerator
3167 * Calls the block with each successive disjoint +n+-tuple of elements;
3171 * (1..10).each_slice(3) {|tuple| a.push(tuple) }
3172 * a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
3175 * h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4}
3176 * h.each_slice(2) {|tuple| a.push(tuple) }
3177 * a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
3179 * With no block given, returns an Enumerator.
3183 enum_each_slice(VALUE obj
, VALUE n
)
3185 long size
= NUM2LONG(n
);
3190 if (size
<= 0) rb_raise(rb_eArgError
, "invalid slice size");
3191 RETURN_SIZED_ENUMERATOR(obj
, 1, &n
, enum_each_slice_size
);
3192 size
= limit_by_enum_size(obj
, size
);
3193 ary
= rb_ary_new2(size
);
3194 arity
= rb_block_arity();
3195 memo
= MEMO_NEW(ary
, dont_recycle_block_arg(arity
), size
);
3196 rb_block_call(obj
, id_each
, 0, 0, each_slice_i
, (VALUE
)memo
);
3198 if (RARRAY_LEN(ary
) > 0) rb_yield(ary
);
3204 each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3206 struct MEMO
*memo
= MEMO_CAST(args
);
3207 VALUE ary
= memo
->v1
;
3209 long size
= memo
->u3
.cnt
;
3212 if (RARRAY_LEN(ary
) == size
) {
3215 rb_ary_push(ary
, i
);
3216 if (RARRAY_LEN(ary
) == size
) {
3218 ary
= rb_ary_dup(ary
);
3226 enum_each_cons_size(VALUE obj
, VALUE args
, VALUE eobj
)
3228 const VALUE zero
= LONG2FIX(0);
3230 long cons_size
= NUM2LONG(RARRAY_AREF(args
, 0));
3231 if (cons_size
<= 0) rb_raise(rb_eArgError
, "invalid size");
3233 size
= enum_size(obj
, 0, 0);
3234 if (NIL_P(size
)) return Qnil
;
3236 n
= add_int(size
, 1 - cons_size
);
3237 return (OPTIMIZED_CMP(n
, zero
) == -1) ? zero
: n
;
3242 * each_cons(n) { ... } -> self
3243 * each_cons(n) -> enumerator
3245 * Calls the block with each successive overlapped +n+-tuple of elements;
3249 * (1..5).each_cons(3) {|element| a.push(element) }
3250 * a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3253 * h = {foo: 0, bar: 1, baz: 2, bam: 3}
3254 * h.each_cons(2) {|element| a.push(element) }
3255 * a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
3257 * With no block given, returns an Enumerator.
3261 enum_each_cons(VALUE obj
, VALUE n
)
3263 long size
= NUM2LONG(n
);
3267 if (size
<= 0) rb_raise(rb_eArgError
, "invalid size");
3268 RETURN_SIZED_ENUMERATOR(obj
, 1, &n
, enum_each_cons_size
);
3269 arity
= rb_block_arity();
3270 if (enum_size_over_p(obj
, size
)) return obj
;
3271 memo
= MEMO_NEW(rb_ary_new2(size
), dont_recycle_block_arg(arity
), size
);
3272 rb_block_call(obj
, id_each
, 0, 0, each_cons_i
, (VALUE
)memo
);
3278 each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, memo
))
3281 return rb_yield_values(2, i
, memo
);
3286 * each_with_object(object) { |(*args), memo_object| ... } -> object
3287 * each_with_object(object) -> enumerator
3289 * Calls the block once for each element, passing both the element
3290 * and the given object:
3292 * (1..4).each_with_object([]) {|i, a| a.push(i**2) }
3293 * # => [1, 4, 9, 16]
3295 * {foo: 0, bar: 1, baz: 2}.each_with_object({}) {|(k, v), h| h[v] = k }
3296 * # => {0=>:foo, 1=>:bar, 2=>:baz}
3298 * With no block given, returns an Enumerator.
3302 enum_each_with_object(VALUE obj
, VALUE memo
)
3304 RETURN_SIZED_ENUMERATOR(obj
, 1, &memo
, enum_size
);
3306 rb_block_call(obj
, id_each
, 0, 0, each_with_object_i
, memo
);
3312 zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val
, memoval
))
3314 struct MEMO
*memo
= (struct MEMO
*)memoval
;
3315 VALUE result
= memo
->v1
;
3316 VALUE args
= memo
->v2
;
3317 long n
= memo
->u3
.cnt
++;
3321 tmp
= rb_ary_new2(RARRAY_LEN(args
) + 1);
3322 rb_ary_store(tmp
, 0, rb_enum_values_pack(argc
, argv
));
3323 for (i
=0; i
<RARRAY_LEN(args
); i
++) {
3324 VALUE e
= RARRAY_AREF(args
, i
);
3326 if (RARRAY_LEN(e
) <= n
) {
3327 rb_ary_push(tmp
, Qnil
);
3330 rb_ary_push(tmp
, RARRAY_AREF(e
, n
));
3333 if (NIL_P(result
)) {
3334 enum_yield_array(tmp
);
3337 rb_ary_push(result
, tmp
);
3348 VALUE
*v
= (VALUE
*)w
;
3349 return v
[0] = rb_funcallv(v
[1], id_next
, 0, 0);
3353 call_stop(VALUE w
, VALUE _
)
3355 VALUE
*v
= (VALUE
*)w
;
3356 return v
[0] = Qundef
;
3360 zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val
, memoval
))
3362 struct MEMO
*memo
= (struct MEMO
*)memoval
;
3363 VALUE result
= memo
->v1
;
3364 VALUE args
= memo
->v2
;
3368 tmp
= rb_ary_new2(RARRAY_LEN(args
) + 1);
3369 rb_ary_store(tmp
, 0, rb_enum_values_pack(argc
, argv
));
3370 for (i
=0; i
<RARRAY_LEN(args
); i
++) {
3371 if (NIL_P(RARRAY_AREF(args
, i
))) {
3372 rb_ary_push(tmp
, Qnil
);
3377 v
[1] = RARRAY_AREF(args
, i
);
3378 rb_rescue2(call_next
, (VALUE
)v
, call_stop
, (VALUE
)v
, rb_eStopIteration
, (VALUE
)0);
3379 if (UNDEF_P(v
[0])) {
3380 RARRAY_ASET(args
, i
, Qnil
);
3383 rb_ary_push(tmp
, v
[0]);
3386 if (NIL_P(result
)) {
3387 enum_yield_array(tmp
);
3390 rb_ary_push(result
, tmp
);
3400 * zip(*other_enums) -> array
3401 * zip(*other_enums) {|array| ... } -> nil
3403 * With no block given, returns a new array +new_array+ of size self.size
3404 * whose elements are arrays.
3405 * Each nested array <tt>new_array[n]</tt>
3406 * is of size <tt>other_enums.size+1</tt>, and contains:
3408 * - The +n+-th element of self.
3409 * - The +n+-th element of each of the +other_enums+.
3411 * If all +other_enums+ and self are the same size,
3412 * all elements are included in the result, and there is no +nil+-filling:
3414 * a = [:a0, :a1, :a2, :a3]
3415 * b = [:b0, :b1, :b2, :b3]
3416 * c = [:c0, :c1, :c2, :c3]
3418 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3420 * f = {foo: 0, bar: 1, baz: 2}
3421 * g = {goo: 3, gar: 4, gaz: 5}
3422 * h = {hoo: 6, har: 7, haz: 8}
3425 * # [[:foo, 0], [:goo, 3], [:hoo, 6]],
3426 * # [[:bar, 1], [:gar, 4], [:har, 7]],
3427 * # [[:baz, 2], [:gaz, 5], [:haz, 8]]
3430 * If any enumerable in other_enums is smaller than self,
3431 * fills to <tt>self.size</tt> with +nil+:
3433 * a = [:a0, :a1, :a2, :a3]
3434 * b = [:b0, :b1, :b2]
3437 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, nil], [:a3, nil, nil]]
3439 * If any enumerable in other_enums is larger than self,
3440 * its trailing elements are ignored:
3442 * a = [:a0, :a1, :a2, :a3]
3443 * b = [:b0, :b1, :b2, :b3, :b4]
3444 * c = [:c0, :c1, :c2, :c3, :c4, :c5]
3446 * d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]
3448 * When a block is given, calls the block with each of the sub-arrays
3449 * (formed as above); returns nil:
3451 * a = [:a0, :a1, :a2, :a3]
3452 * b = [:b0, :b1, :b2, :b3]
3453 * c = [:c0, :c1, :c2, :c3]
3454 * a.zip(b, c) {|sub_array| p sub_array} # => nil
3466 enum_zip(int argc
, VALUE
*argv
, VALUE obj
)
3471 VALUE result
= Qnil
;
3472 VALUE args
= rb_ary_new4(argc
, argv
);
3475 argv
= RARRAY_PTR(args
);
3476 for (i
=0; i
<argc
; i
++) {
3477 VALUE ary
= rb_check_array_type(argv
[i
]);
3485 static const VALUE sym_each
= STATIC_ID2SYM(id_each
);
3486 CONST_ID(conv
, "to_enum");
3487 for (i
=0; i
<argc
; i
++) {
3488 if (!rb_respond_to(argv
[i
], id_each
)) {
3489 rb_raise(rb_eTypeError
, "wrong argument type %"PRIsVALUE
" (must respond to :each)",
3490 rb_obj_class(argv
[i
]));
3492 argv
[i
] = rb_funcallv(argv
[i
], conv
, 1, &sym_each
);
3495 if (!rb_block_given_p()) {
3496 result
= rb_ary_new();
3499 /* TODO: use NODE_DOT2 as memo(v, v, -) */
3500 memo
= MEMO_NEW(result
, args
, 0);
3501 rb_block_call(obj
, id_each
, 0, 0, allary
? zip_ary
: zip_i
, (VALUE
)memo
);
3507 take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3509 struct MEMO
*memo
= MEMO_CAST(args
);
3510 rb_ary_push(memo
->v1
, rb_enum_values_pack(argc
, argv
));
3511 if (--memo
->u3
.cnt
== 0) rb_iter_break();
3519 * For non-negative integer +n+, returns the first +n+ elements:
3522 * r.take(2) # => [1, 2]
3525 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3526 * h.take(2) # => [[:foo, 0], [:bar, 1]]
3531 enum_take(VALUE obj
, VALUE n
)
3535 long len
= NUM2LONG(n
);
3538 rb_raise(rb_eArgError
, "attempt to take negative size");
3541 if (len
== 0) return rb_ary_new2(0);
3542 result
= rb_ary_new2(len
);
3543 memo
= MEMO_NEW(result
, 0, len
);
3544 rb_block_call(obj
, id_each
, 0, 0, take_i
, (VALUE
)memo
);
3550 take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
3552 if (!RTEST(rb_yield_values2(argc
, argv
))) rb_iter_break();
3553 rb_ary_push(ary
, rb_enum_values_pack(argc
, argv
));
3559 * take_while {|element| ... } -> array
3560 * take_while -> enumerator
3562 * Calls the block with successive elements as long as the block
3563 * returns a truthy value;
3564 * returns an array of all elements up to that point:
3567 * (1..4).take_while{|i| i < 3 } # => [1, 2]
3568 * h = {foo: 0, bar: 1, baz: 2}
3569 * h.take_while{|element| key, value = *element; value < 2 }
3570 * # => [[:foo, 0], [:bar, 1]]
3572 * With no block given, returns an Enumerator.
3577 enum_take_while(VALUE obj
)
3581 RETURN_ENUMERATOR(obj
, 0, 0);
3583 rb_block_call(obj
, id_each
, 0, 0, take_while_i
, ary
);
3588 drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3590 struct MEMO
*memo
= MEMO_CAST(args
);
3591 if (memo
->u3
.cnt
== 0) {
3592 rb_ary_push(memo
->v1
, rb_enum_values_pack(argc
, argv
));
3604 * For positive integer +n+, returns an array containing
3605 * all but the first +n+ elements:
3608 * r.drop(3) # => [4]
3609 * r.drop(2) # => [3, 4]
3610 * r.drop(1) # => [2, 3, 4]
3611 * r.drop(0) # => [1, 2, 3, 4]
3612 * r.drop(50) # => []
3614 * h = {foo: 0, bar: 1, baz: 2, bat: 3}
3615 * h.drop(2) # => [[:baz, 2], [:bat, 3]]
3620 enum_drop(VALUE obj
, VALUE n
)
3624 long len
= NUM2LONG(n
);
3627 rb_raise(rb_eArgError
, "attempt to drop negative size");
3630 result
= rb_ary_new();
3631 memo
= MEMO_NEW(result
, 0, len
);
3632 rb_block_call(obj
, id_each
, 0, 0, drop_i
, (VALUE
)memo
);
3638 drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
3640 struct MEMO
*memo
= MEMO_CAST(args
);
3643 if (!memo
->u3
.state
&& !RTEST(enum_yield(argc
, i
))) {
3644 memo
->u3
.state
= TRUE
;
3646 if (memo
->u3
.state
) {
3647 rb_ary_push(memo
->v1
, i
);
3654 * drop_while {|element| ... } -> array
3655 * drop_while -> enumerator
3657 * Calls the block with successive elements as long as the block
3658 * returns a truthy value;
3659 * returns an array of all elements after that point:
3662 * (1..4).drop_while{|i| i < 3 } # => [3, 4]
3663 * h = {foo: 0, bar: 1, baz: 2}
3664 * a = h.drop_while{|element| key, value = *element; value < 2 }
3665 * a # => [[:baz, 2]]
3667 * With no block given, returns an Enumerator.
3672 enum_drop_while(VALUE obj
)
3677 RETURN_ENUMERATOR(obj
, 0, 0);
3678 result
= rb_ary_new();
3679 memo
= MEMO_NEW(result
, 0, FALSE
);
3680 rb_block_call(obj
, id_each
, 0, 0, drop_while_i
, (VALUE
)memo
);
3685 cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
3689 rb_ary_push(ary
, argc
> 1 ? i
: rb_ary_new_from_values(argc
, argv
));
3690 enum_yield(argc
, i
);
3695 enum_cycle_size(VALUE self
, VALUE args
, VALUE eobj
)
3701 if (args
&& (RARRAY_LEN(args
) > 0)) {
3702 n
= RARRAY_AREF(args
, 0);
3703 if (!NIL_P(n
)) mul
= NUM2LONG(n
);
3706 size
= enum_size(self
, args
, 0);
3707 if (NIL_P(size
) || FIXNUM_ZERO_P(size
)) return size
;
3709 if (NIL_P(n
)) return DBL2NUM(HUGE_VAL
);
3710 if (mul
<= 0) return INT2FIX(0);
3712 return rb_funcallv(size
, '*', 1, &n
);
3717 * cycle(n = nil) {|element| ...} -> nil
3718 * cycle(n = nil) -> enumerator
3720 * When called with positive integer argument +n+ and a block,
3721 * calls the block with each element, then does so again,
3722 * until it has done so +n+ times; returns +nil+:
3725 * (1..4).cycle(3) {|element| a.push(element) } # => nil
3726 * a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
3728 * ('a'..'d').cycle(2) {|element| a.push(element) }
3729 * a # => ["a", "b", "c", "d", "a", "b", "c", "d"]
3731 * {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) }
3732 * a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
3734 * If count is zero or negative, does not call the block.
3736 * When called with a block and +n+ is +nil+, cycles forever.
3738 * When no block is given, returns an Enumerator.
3743 enum_cycle(int argc
, VALUE
*argv
, VALUE obj
)
3749 rb_check_arity(argc
, 0, 1);
3751 RETURN_SIZED_ENUMERATOR(obj
, argc
, argv
, enum_cycle_size
);
3752 if (!argc
|| NIL_P(nv
= argv
[0])) {
3757 if (n
<= 0) return Qnil
;
3760 RBASIC_CLEAR_CLASS(ary
);
3761 rb_block_call(obj
, id_each
, 0, 0, cycle_i
, ary
);
3762 len
= RARRAY_LEN(ary
);
3763 if (len
== 0) return Qnil
;
3764 while (n
< 0 || 0 < --n
) {
3765 for (i
=0; i
<len
; i
++) {
3766 enum_yield_array(RARRAY_AREF(ary
, i
));
3780 chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _argp
))
3782 struct chunk_arg
*argp
= MEMO_FOR(struct chunk_arg
, _argp
);
3784 VALUE alone
= ID2SYM(id__alone
);
3785 VALUE separator
= ID2SYM(id__separator
);
3789 v
= rb_funcallv(argp
->categorize
, id_call
, 1, &i
);
3792 if (!NIL_P(argp
->prev_value
)) {
3793 s
= rb_assoc_new(argp
->prev_value
, argp
->prev_elts
);
3794 rb_funcallv(argp
->yielder
, id_lshift
, 1, &s
);
3795 argp
->prev_value
= argp
->prev_elts
= Qnil
;
3797 v
= rb_assoc_new(v
, rb_ary_new3(1, i
));
3798 rb_funcallv(argp
->yielder
, id_lshift
, 1, &v
);
3800 else if (NIL_P(v
) || v
== separator
) {
3801 if (!NIL_P(argp
->prev_value
)) {
3802 v
= rb_assoc_new(argp
->prev_value
, argp
->prev_elts
);
3803 rb_funcallv(argp
->yielder
, id_lshift
, 1, &v
);
3804 argp
->prev_value
= argp
->prev_elts
= Qnil
;
3807 else if (SYMBOL_P(v
) && (s
= rb_sym2str(v
), RSTRING_PTR(s
)[0] == '_')) {
3808 rb_raise(rb_eRuntimeError
, "symbols beginning with an underscore are reserved");
3811 if (NIL_P(argp
->prev_value
)) {
3812 argp
->prev_value
= v
;
3813 argp
->prev_elts
= rb_ary_new3(1, i
);
3816 if (rb_equal(argp
->prev_value
, v
)) {
3817 rb_ary_push(argp
->prev_elts
, i
);
3820 s
= rb_assoc_new(argp
->prev_value
, argp
->prev_elts
);
3821 rb_funcallv(argp
->yielder
, id_lshift
, 1, &s
);
3822 argp
->prev_value
= v
;
3823 argp
->prev_elts
= rb_ary_new3(1, i
);
3831 chunk_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
3835 struct chunk_arg
*memo
= NEW_MEMO_FOR(struct chunk_arg
, arg
);
3837 enumerable
= rb_ivar_get(enumerator
, id_chunk_enumerable
);
3838 memo
->categorize
= rb_ivar_get(enumerator
, id_chunk_categorize
);
3839 memo
->prev_value
= Qnil
;
3840 memo
->prev_elts
= Qnil
;
3841 memo
->yielder
= yielder
;
3843 rb_block_call(enumerable
, id_each
, 0, 0, chunk_ii
, arg
);
3844 memo
= MEMO_FOR(struct chunk_arg
, arg
);
3845 if (!NIL_P(memo
->prev_elts
)) {
3846 arg
= rb_assoc_new(memo
->prev_value
, memo
->prev_elts
);
3847 rb_funcallv(memo
->yielder
, id_lshift
, 1, &arg
);
3854 * chunk {|array| ... } -> enumerator
3856 * Each element in the returned enumerator is a 2-element array consisting of:
3858 * - A value returned by the block.
3859 * - An array ("chunk") containing the element for which that value was returned,
3860 * and all following elements for which the block returned the same value:
3864 * - Each block return value that is different from its predecessor
3865 * begins a new chunk.
3866 * - Each block return value that is the same as its predecessor
3867 * continues the same chunk.
3871 * e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...>
3872 * # The enumerator elements.
3873 * e.next # => [0, [0, 1, 2]]
3874 * e.next # => [1, [3, 4, 5]]
3875 * e.next # => [2, [6, 7, 8]]
3876 * e.next # => [3, [9, 10]]
3878 * \Method +chunk+ is especially useful for an enumerable that is already sorted.
3879 * This example counts words for each initial letter in a large array of words:
3881 * # Get sorted words from a web page.
3882 * url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt'
3883 * words = URI::open(url).readlines
3884 * # Make chunks, one for each letter.
3885 * e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...>
3886 * # Display 'A' through 'F'.
3887 * e.each {|c, words| p [c, words.length]; break if c == 'F' }
3898 * You can use the special symbol <tt>:_alone</tt> to force an element
3899 * into its own separate chuck:
3902 * e = a.chunk{|i| i.even? ? :_alone : true }
3903 * e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
3905 * For example, you can put each line that contains a URL into its own chunk:
3908 * open(filename) { |f|
3909 * f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
3914 * You can use the special symbol <tt>:_separator</tt> or +nil+
3915 * to force an element to be ignored (not included in any chunk):
3917 * a = [0, 0, -1, 1, 1]
3918 * e = a.chunk{|i| i < 0 ? :_separator : true }
3919 * e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
3921 * Note that the separator does end the chunk:
3923 * a = [0, 0, -1, 1, -1, 1]
3924 * e = a.chunk{|i| i < 0 ? :_separator : true }
3925 * e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
3927 * For example, the sequence of hyphens in svn log can be eliminated as follows:
3929 * sep = "-"*72 + "\n"
3930 * IO.popen("svn log README") { |f|
3932 * line != sep || nil
3933 * }.each { |_, lines|
3937 * #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
3939 * # "* README, README.ja: Update the portability section.\n",
3941 * # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
3943 * # "* README, README.ja: Add a note about default C flags.\n",
3947 * Paragraphs separated by empty lines can be parsed as follows:
3949 * File.foreach("README").chunk { |line|
3950 * /\A\s*\z/ !~ line || nil
3951 * }.each { |_, lines|
3957 enum_chunk(VALUE enumerable
)
3961 RETURN_SIZED_ENUMERATOR(enumerable
, 0, 0, enum_size
);
3963 enumerator
= rb_obj_alloc(rb_cEnumerator
);
3964 rb_ivar_set(enumerator
, id_chunk_enumerable
, enumerable
);
3965 rb_ivar_set(enumerator
, id_chunk_categorize
, rb_block_proc());
3966 rb_block_call(enumerator
, idInitialize
, 0, 0, chunk_i
, enumerator
);
3971 struct slicebefore_arg
{
3979 slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _argp
))
3981 struct slicebefore_arg
*argp
= MEMO_FOR(struct slicebefore_arg
, _argp
);
3986 if (!NIL_P(argp
->sep_pat
))
3987 header_p
= rb_funcallv(argp
->sep_pat
, id_eqq
, 1, &i
);
3989 header_p
= rb_funcallv(argp
->sep_pred
, id_call
, 1, &i
);
3990 if (RTEST(header_p
)) {
3991 if (!NIL_P(argp
->prev_elts
))
3992 rb_funcallv(argp
->yielder
, id_lshift
, 1, &argp
->prev_elts
);
3993 argp
->prev_elts
= rb_ary_new3(1, i
);
3996 if (NIL_P(argp
->prev_elts
))
3997 argp
->prev_elts
= rb_ary_new3(1, i
);
3999 rb_ary_push(argp
->prev_elts
, i
);
4006 slicebefore_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
4010 struct slicebefore_arg
*memo
= NEW_MEMO_FOR(struct slicebefore_arg
, arg
);
4012 enumerable
= rb_ivar_get(enumerator
, id_slicebefore_enumerable
);
4013 memo
->sep_pred
= rb_attr_get(enumerator
, id_slicebefore_sep_pred
);
4014 memo
->sep_pat
= NIL_P(memo
->sep_pred
) ? rb_ivar_get(enumerator
, id_slicebefore_sep_pat
) : Qnil
;
4015 memo
->prev_elts
= Qnil
;
4016 memo
->yielder
= yielder
;
4018 rb_block_call(enumerable
, id_each
, 0, 0, slicebefore_ii
, arg
);
4019 memo
= MEMO_FOR(struct slicebefore_arg
, arg
);
4020 if (!NIL_P(memo
->prev_elts
))
4021 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4027 * slice_before(pattern) -> enumerator
4028 * slice_before {|elt| ... } -> enumerator
4030 * With argument +pattern+, returns an enumerator that uses the pattern
4031 * to partition elements into arrays ("slices").
4032 * An element begins a new slice if <tt>element === pattern</tt>
4033 * (or if it is the first element).
4035 * a = %w[foo bar fop for baz fob fog bam foy]
4036 * e = a.slice_before(/ba/) # => #<Enumerator: ...>
4037 * e.each {|array| p array }
4042 * ["bar", "fop", "for"]
4043 * ["baz", "fob", "fog"]
4046 * With a block, returns an enumerator that uses the block
4047 * to partition elements into arrays.
4048 * An element begins a new slice if its block return is a truthy value
4049 * (or if it is the first element):
4051 * e = (1..20).slice_before {|i| i % 4 == 2 } # => #<Enumerator: ...>
4052 * e.each {|array| p array }
4063 * Other methods of the Enumerator class and Enumerable module,
4064 * such as +to_a+, +map+, etc., are also usable.
4066 * For example, iteration over ChangeLog entries can be implemented as
4069 * # iterate over ChangeLog entries.
4070 * open("ChangeLog") { |f|
4071 * f.slice_before(/\A\S/).each { |e| pp e }
4074 * # same as above. block is used instead of pattern argument.
4075 * open("ChangeLog") { |f|
4076 * f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
4079 * "svn proplist -R" produces multiline output for each file.
4080 * They can be chunked as follows:
4082 * IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
4083 * f.lines.slice_before(/\AProp/).each { |lines| p lines }
4085 * #=> ["Properties on '.':\n", " svn:ignore\n", " svk:merge\n"]
4086 * # ["Properties on 'goruby.c':\n", " svn:eol-style\n"]
4087 * # ["Properties on 'complex.c':\n", " svn:mime-type\n", " svn:eol-style\n"]
4088 * # ["Properties on 'regparse.c':\n", " svn:eol-style\n"]
4091 * If the block needs to maintain state over multiple elements,
4092 * local variables can be used.
4093 * For example, three or more consecutive increasing numbers can be squashed
4094 * as follows (see +chunk_while+ for a better way):
4096 * a = [0, 2, 3, 4, 6, 7, 9]
4098 * p a.slice_before { |e|
4099 * prev, prev2 = e, prev
4102 * es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
4106 * However local variables should be used carefully
4107 * if the result enumerator is enumerated twice or more.
4108 * The local variables should be initialized for each enumeration.
4109 * Enumerator.new can be used to do it.
4111 * # Word wrapping. This assumes all characters have same width.
4112 * def wordwrap(words, maxwidth)
4113 * Enumerator.new {|y|
4114 * # cols is initialized in Enumerator.new.
4116 * words.slice_before { |w|
4117 * cols += 1 if cols != 0
4119 * if maxwidth < cols
4125 * }.each {|ws| y.yield ws }
4128 * text = (1..20).to_a.join(" ")
4129 * enum = wordwrap(text.split(/\s+/), 10)
4131 * enum.each { |ws| puts ws.join(" ") } # first enumeration.
4133 * enum.each { |ws| puts ws.join(" ") } # second enumeration generates same result as the first.
4151 * mbox contains series of mails which start with Unix From line.
4152 * So each mail can be extracted by slice before Unix From line.
4155 * open("mbox") { |f|
4156 * f.slice_before { |line|
4157 * line.start_with? "From "
4159 * unix_from = mail.shift
4160 * i = mail.index("\n")
4161 * header = mail[0...i]
4162 * body = mail[(i+1)..-1]
4163 * body.pop if body.last == "\n"
4164 * fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
4171 * # split mails in mbox (slice before Unix From line after an empty line)
4172 * open("mbox") { |f|
4174 * f.slice_before { |line|
4176 * emp = line == "\n"
4177 * prevemp && line.start_with?("From ")
4179 * mail.pop if mail.last == "\n"
4186 enum_slice_before(int argc
, VALUE
*argv
, VALUE enumerable
)
4190 if (rb_block_given_p()) {
4192 rb_error_arity(argc
, 0, 0);
4193 enumerator
= rb_obj_alloc(rb_cEnumerator
);
4194 rb_ivar_set(enumerator
, id_slicebefore_sep_pred
, rb_block_proc());
4198 rb_scan_args(argc
, argv
, "1", &sep_pat
);
4199 enumerator
= rb_obj_alloc(rb_cEnumerator
);
4200 rb_ivar_set(enumerator
, id_slicebefore_sep_pat
, sep_pat
);
4202 rb_ivar_set(enumerator
, id_slicebefore_enumerable
, enumerable
);
4203 rb_block_call(enumerator
, idInitialize
, 0, 0, slicebefore_i
, enumerator
);
4208 struct sliceafter_arg
{
4216 sliceafter_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
4218 #define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct sliceafter_arg, _memo)))
4219 struct sliceafter_arg
*memo
;
4225 if (NIL_P(memo
->prev_elts
)) {
4226 memo
->prev_elts
= rb_ary_new3(1, i
);
4229 rb_ary_push(memo
->prev_elts
, i
);
4232 if (NIL_P(memo
->pred
)) {
4233 split_p
= RTEST(rb_funcallv(memo
->pat
, id_eqq
, 1, &i
));
4237 split_p
= RTEST(rb_funcallv(memo
->pred
, id_call
, 1, &i
));
4242 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4244 memo
->prev_elts
= Qnil
;
4252 sliceafter_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
4256 struct sliceafter_arg
*memo
= NEW_MEMO_FOR(struct sliceafter_arg
, arg
);
4258 enumerable
= rb_ivar_get(enumerator
, id_sliceafter_enum
);
4259 memo
->pat
= rb_ivar_get(enumerator
, id_sliceafter_pat
);
4260 memo
->pred
= rb_attr_get(enumerator
, id_sliceafter_pred
);
4261 memo
->prev_elts
= Qnil
;
4262 memo
->yielder
= yielder
;
4264 rb_block_call(enumerable
, id_each
, 0, 0, sliceafter_ii
, arg
);
4265 memo
= MEMO_FOR(struct sliceafter_arg
, arg
);
4266 if (!NIL_P(memo
->prev_elts
))
4267 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4273 * enum.slice_after(pattern) -> an_enumerator
4274 * enum.slice_after { |elt| bool } -> an_enumerator
4276 * Creates an enumerator for each chunked elements.
4277 * The ends of chunks are defined by _pattern_ and the block.
4279 * If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
4280 * returns <code>true</code> for the element, the element is end of a
4283 * The <code>===</code> and _block_ is called from the first element to the last
4284 * element of _enum_.
4286 * The result enumerator yields the chunked elements as an array.
4287 * So +each+ method can be called as follows:
4289 * enum.slice_after(pattern).each { |ary| ... }
4290 * enum.slice_after { |elt| bool }.each { |ary| ... }
4292 * Other methods of the Enumerator class and Enumerable module,
4293 * such as +map+, etc., are also usable.
4295 * For example, continuation lines (lines end with backslash) can be
4296 * concatenated as follows:
4298 * lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
4299 * e = lines.slice_after(/(?<!\\)\n\z/)
4301 * #=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
4302 * p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
4303 * #=>["foo\n", "barbaz\n", "\n", "qux\n"]
4308 enum_slice_after(int argc
, VALUE
*argv
, VALUE enumerable
)
4311 VALUE pat
= Qnil
, pred
= Qnil
;
4313 if (rb_block_given_p()) {
4315 rb_raise(rb_eArgError
, "both pattern and block are given");
4316 pred
= rb_block_proc();
4319 rb_scan_args(argc
, argv
, "1", &pat
);
4322 enumerator
= rb_obj_alloc(rb_cEnumerator
);
4323 rb_ivar_set(enumerator
, id_sliceafter_enum
, enumerable
);
4324 rb_ivar_set(enumerator
, id_sliceafter_pat
, pat
);
4325 rb_ivar_set(enumerator
, id_sliceafter_pred
, pred
);
4327 rb_block_call(enumerator
, idInitialize
, 0, 0, sliceafter_i
, enumerator
);
4331 struct slicewhen_arg
{
4336 int inverted
; /* 0 for slice_when and 1 for chunk_while. */
4340 slicewhen_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i
, _memo
))
4342 #define UPDATE_MEMO ((void)(memo = MEMO_FOR(struct slicewhen_arg, _memo)))
4343 struct slicewhen_arg
*memo
;
4349 if (UNDEF_P(memo
->prev_elt
)) {
4350 /* The first element */
4352 memo
->prev_elts
= rb_ary_new3(1, i
);
4356 args
[0] = memo
->prev_elt
;
4358 split_p
= RTEST(rb_funcallv(memo
->pred
, id_call
, 2, args
));
4365 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4367 memo
->prev_elts
= rb_ary_new3(1, i
);
4370 rb_ary_push(memo
->prev_elts
, i
);
4381 slicewhen_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder
, enumerator
))
4385 struct slicewhen_arg
*memo
=
4386 NEW_PARTIAL_MEMO_FOR(struct slicewhen_arg
, arg
, inverted
);
4388 enumerable
= rb_ivar_get(enumerator
, id_slicewhen_enum
);
4389 memo
->pred
= rb_attr_get(enumerator
, id_slicewhen_pred
);
4390 memo
->prev_elt
= Qundef
;
4391 memo
->prev_elts
= Qnil
;
4392 memo
->yielder
= yielder
;
4393 memo
->inverted
= RTEST(rb_attr_get(enumerator
, id_slicewhen_inverted
));
4395 rb_block_call(enumerable
, id_each
, 0, 0, slicewhen_ii
, arg
);
4396 memo
= MEMO_FOR(struct slicewhen_arg
, arg
);
4397 if (!NIL_P(memo
->prev_elts
))
4398 rb_funcallv(memo
->yielder
, id_lshift
, 1, &memo
->prev_elts
);
4404 * enum.slice_when {|elt_before, elt_after| bool } -> an_enumerator
4406 * Creates an enumerator for each chunked elements.
4407 * The beginnings of chunks are defined by the block.
4409 * This method splits each chunk using adjacent elements,
4410 * _elt_before_ and _elt_after_,
4411 * in the receiver enumerator.
4412 * This method split chunks between _elt_before_ and _elt_after_ where
4413 * the block returns <code>true</code>.
4415 * The block is called the length of the receiver enumerator minus one.
4417 * The result enumerator yields the chunked elements as an array.
4418 * So +each+ method can be called as follows:
4420 * enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }
4422 * Other methods of the Enumerator class and Enumerable module,
4423 * such as +to_a+, +map+, etc., are also usable.
4425 * For example, one-by-one increasing subsequence can be chunked as follows:
4427 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4428 * b = a.slice_when {|i, j| i+1 != j }
4429 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4430 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4431 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4433 * p d #=> "1,2,4,9-12,15,16,19-21"
4435 * Near elements (threshold: 6) in sorted array can be chunked as follows:
4437 * a = [3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
4438 * p a.slice_when {|i, j| 6 < j - i }.to_a
4439 * #=> [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
4441 * Increasing (non-decreasing) subsequence can be chunked as follows:
4443 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4444 * p a.slice_when {|i, j| i > j }.to_a
4445 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4447 * Adjacent evens and odds can be chunked as follows:
4448 * (Enumerable#chunk is another way to do it.)
4450 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4451 * p a.slice_when {|i, j| i.even? != j.even? }.to_a
4452 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4454 * Paragraphs (non-empty lines with trailing empty lines) can be chunked as follows:
4455 * (See Enumerable#chunk to ignore empty lines.)
4457 * lines = ["foo\n", "bar\n", "\n", "baz\n", "qux\n"]
4458 * p lines.slice_when {|l1, l2| /\A\s*\z/ =~ l1 && /\S/ =~ l2 }.to_a
4459 * #=> [["foo\n", "bar\n", "\n"], ["baz\n", "qux\n"]]
4461 * Enumerable#chunk_while does the same, except splitting when the block
4462 * returns <code>false</code> instead of <code>true</code>.
4465 enum_slice_when(VALUE enumerable
)
4470 pred
= rb_block_proc();
4472 enumerator
= rb_obj_alloc(rb_cEnumerator
);
4473 rb_ivar_set(enumerator
, id_slicewhen_enum
, enumerable
);
4474 rb_ivar_set(enumerator
, id_slicewhen_pred
, pred
);
4475 rb_ivar_set(enumerator
, id_slicewhen_inverted
, Qfalse
);
4477 rb_block_call(enumerator
, idInitialize
, 0, 0, slicewhen_i
, enumerator
);
4483 * enum.chunk_while {|elt_before, elt_after| bool } -> an_enumerator
4485 * Creates an enumerator for each chunked elements.
4486 * The beginnings of chunks are defined by the block.
4488 * This method splits each chunk using adjacent elements,
4489 * _elt_before_ and _elt_after_,
4490 * in the receiver enumerator.
4491 * This method split chunks between _elt_before_ and _elt_after_ where
4492 * the block returns <code>false</code>.
4494 * The block is called the length of the receiver enumerator minus one.
4496 * The result enumerator yields the chunked elements as an array.
4497 * So +each+ method can be called as follows:
4499 * enum.chunk_while { |elt_before, elt_after| bool }.each { |ary| ... }
4501 * Other methods of the Enumerator class and Enumerable module,
4502 * such as +to_a+, +map+, etc., are also usable.
4504 * For example, one-by-one increasing subsequence can be chunked as follows:
4506 * a = [1,2,4,9,10,11,12,15,16,19,20,21]
4507 * b = a.chunk_while {|i, j| i+1 == j }
4508 * p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
4509 * c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
4510 * p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
4512 * p d #=> "1,2,4,9-12,15,16,19-21"
4514 * Increasing (non-decreasing) subsequence can be chunked as follows:
4516 * a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
4517 * p a.chunk_while {|i, j| i <= j }.to_a
4518 * #=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
4520 * Adjacent evens and odds can be chunked as follows:
4521 * (Enumerable#chunk is another way to do it.)
4523 * a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
4524 * p a.chunk_while {|i, j| i.even? == j.even? }.to_a
4525 * #=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
4527 * Enumerable#slice_when does the same, except splitting when the block
4528 * returns <code>true</code> instead of <code>false</code>.
4531 enum_chunk_while(VALUE enumerable
)
4536 pred
= rb_block_proc();
4538 enumerator
= rb_obj_alloc(rb_cEnumerator
);
4539 rb_ivar_set(enumerator
, id_slicewhen_enum
, enumerable
);
4540 rb_ivar_set(enumerator
, id_slicewhen_pred
, pred
);
4541 rb_ivar_set(enumerator
, id_slicewhen_inverted
, Qtrue
);
4543 rb_block_call(enumerator
, idInitialize
, 0, 0, slicewhen_i
, enumerator
);
4547 struct enum_sum_memo
{
4556 sum_iter_normalize_memo(struct enum_sum_memo
*memo
)
4558 RUBY_ASSERT(FIXABLE(memo
->n
));
4559 memo
->v
= rb_fix_plus(LONG2FIX(memo
->n
), memo
->v
);
4562 switch (TYPE(memo
->r
)) {
4563 case T_RATIONAL
: memo
->v
= rb_rational_plus(memo
->r
, memo
->v
); break;
4564 case T_UNDEF
: break;
4565 default: UNREACHABLE
; /* or ...? */
4571 sum_iter_fixnum(VALUE i
, struct enum_sum_memo
*memo
)
4573 memo
->n
+= FIX2LONG(i
); /* should not overflow long type */
4574 if (! FIXABLE(memo
->n
)) {
4575 memo
->v
= rb_big_plus(LONG2NUM(memo
->n
), memo
->v
);
4581 sum_iter_bignum(VALUE i
, struct enum_sum_memo
*memo
)
4583 memo
->v
= rb_big_plus(i
, memo
->v
);
4587 sum_iter_rational(VALUE i
, struct enum_sum_memo
*memo
)
4589 if (UNDEF_P(memo
->r
)) {
4593 memo
->r
= rb_rational_plus(memo
->r
, i
);
4598 sum_iter_some_value(VALUE i
, struct enum_sum_memo
*memo
)
4600 memo
->v
= rb_funcallv(memo
->v
, idPLUS
, 1, &i
);
4604 sum_iter_Kahan_Babuska(VALUE i
, struct enum_sum_memo
*memo
)
4607 * Kahan-Babuska balancing compensated summation algorithm
4608 * See https://link.springer.com/article/10.1007/s00607-005-0139-x
4613 case T_FLOAT
: x
= RFLOAT_VALUE(i
); break;
4614 case T_FIXNUM
: x
= FIX2LONG(i
); break;
4615 case T_BIGNUM
: x
= rb_big2dbl(i
); break;
4616 case T_RATIONAL
: x
= rb_num2dbl(i
); break;
4618 memo
->v
= DBL2NUM(memo
->f
);
4619 memo
->float_value
= 0;
4620 sum_iter_some_value(i
, memo
);
4629 else if (! isfinite(x
)) {
4630 if (isinf(x
) && isinf(f
) && signbit(x
) != signbit(f
)) {
4638 else if (isinf(f
)) {
4645 if (fabs(f
) >= fabs(x
)) {
4658 sum_iter(VALUE i
, struct enum_sum_memo
*memo
)
4660 RUBY_ASSERT(memo
!= NULL
);
4661 if (memo
->block_given
) {
4665 if (memo
->float_value
) {
4666 sum_iter_Kahan_Babuska(i
, memo
);
4668 else switch (TYPE(memo
->v
)) {
4669 default: sum_iter_some_value(i
, memo
); return;
4670 case T_FLOAT
: sum_iter_Kahan_Babuska(i
, memo
); return;
4675 case T_FIXNUM
: sum_iter_fixnum(i
, memo
); return;
4676 case T_BIGNUM
: sum_iter_bignum(i
, memo
); return;
4677 case T_RATIONAL
: sum_iter_rational(i
, memo
); return;
4679 sum_iter_normalize_memo(memo
);
4680 memo
->f
= NUM2DBL(memo
->v
);
4682 memo
->float_value
= 1;
4683 sum_iter_Kahan_Babuska(i
, memo
);
4686 sum_iter_normalize_memo(memo
);
4687 sum_iter_some_value(i
, memo
);
4694 enum_sum_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, args
))
4697 sum_iter(i
, (struct enum_sum_memo
*) args
);
4702 hash_sum_i(VALUE key
, VALUE value
, VALUE arg
)
4704 sum_iter(rb_assoc_new(key
, value
), (struct enum_sum_memo
*) arg
);
4709 hash_sum(VALUE hash
, struct enum_sum_memo
*memo
)
4711 RUBY_ASSERT(RB_TYPE_P(hash
, T_HASH
));
4712 RUBY_ASSERT(memo
!= NULL
);
4714 rb_hash_foreach(hash
, hash_sum_i
, (VALUE
)memo
);
4718 int_range_sum(VALUE beg
, VALUE end
, int excl
, VALUE init
)
4722 end
= LONG2FIX(FIX2LONG(end
) - 1);
4724 end
= rb_big_minus(end
, LONG2FIX(1));
4727 if (rb_int_ge(end
, beg
)) {
4729 a
= rb_int_plus(rb_int_minus(end
, beg
), LONG2FIX(1));
4730 a
= rb_int_mul(a
, rb_int_plus(end
, beg
));
4731 a
= rb_int_idiv(a
, LONG2FIX(2));
4732 return rb_int_plus(init
, a
);
4740 * sum(initial_value = 0) -> number
4741 * sum(initial_value = 0) {|element| ... } -> object
4743 * With no block given,
4744 * returns the sum of +initial_value+ and the elements:
4746 * (1..100).sum # => 5050
4747 * (1..100).sum(1) # => 5051
4748 * ('a'..'d').sum('foo') # => "fooabcd"
4750 * Generally, the sum is computed using methods <tt>+</tt> and +each+;
4751 * for performance optimizations, those methods may not be used,
4752 * and so any redefinition of those methods may not have effect here.
4754 * One such optimization: When possible, computes using Gauss's summation
4755 * formula <em>n(n+1)/2</em>:
4757 * 100 * (100 + 1) / 2 # => 5050
4759 * With a block given, calls the block with each element;
4760 * returns the sum of +initial_value+ and the block return values:
4762 * (1..4).sum {|i| i*i } # => 30
4763 * (1..4).sum(100) {|i| i*i } # => 130
4764 * h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
4765 * h.sum {|key, value| value.odd? ? value : 0 } # => 9
4766 * ('a'..'f').sum('x') {|c| c < 'd' ? c : '' } # => "xabc"
4770 enum_sum(int argc
, VALUE
* argv
, VALUE obj
)
4772 struct enum_sum_memo memo
;
4776 memo
.v
= (rb_check_arity(argc
, 0, 1) == 0) ? LONG2FIX(0) : argv
[0];
4777 memo
.block_given
= rb_block_given_p();
4781 if ((memo
.float_value
= RB_FLOAT_TYPE_P(memo
.v
))) {
4782 memo
.f
= RFLOAT_VALUE(memo
.v
);
4790 if (RTEST(rb_range_values(obj
, &beg
, &end
, &excl
))) {
4791 if (!memo
.block_given
&& !memo
.float_value
&&
4792 (FIXNUM_P(beg
) || RB_BIGNUM_TYPE_P(beg
)) &&
4793 (FIXNUM_P(end
) || RB_BIGNUM_TYPE_P(end
))) {
4794 return int_range_sum(beg
, end
, excl
, memo
.v
);
4798 if (RB_TYPE_P(obj
, T_HASH
) &&
4799 rb_method_basic_definition_p(CLASS_OF(obj
), id_each
))
4800 hash_sum(obj
, &memo
);
4802 rb_block_call(obj
, id_each
, 0, 0, enum_sum_i
, (VALUE
)&memo
);
4804 if (memo
.float_value
) {
4805 return DBL2NUM(memo
.f
+ memo
.c
);
4809 memo
.v
= rb_fix_plus(LONG2FIX(memo
.n
), memo
.v
);
4810 if (!UNDEF_P(memo
.r
)) {
4811 memo
.v
= rb_rational_plus(memo
.r
, memo
.v
);
4818 uniq_func(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
4821 rb_hash_add_new_element(hash
, i
, i
);
4826 uniq_iter(RB_BLOCK_CALL_FUNC_ARGLIST(i
, hash
))
4829 rb_hash_add_new_element(hash
, rb_yield_values2(argc
, argv
), i
);
4836 * uniq {|element| ... } -> array
4838 * With no block, returns a new array containing only unique elements;
4839 * the array has no two elements +e0+ and +e1+ such that <tt>e0.eql?(e1)</tt>:
4841 * %w[a b c c b a a b c].uniq # => ["a", "b", "c"]
4842 * [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
4844 * With a block, returns a new array containing elements only for which the block
4845 * returns a unique value:
4847 * a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
4848 * a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4]
4849 * a = %w[a b c d e e d c b a a b c d e]
4850 * a.uniq {|c| c < 'c' } # => ["a", "c"]
4855 enum_uniq(VALUE obj
)
4858 rb_block_call_func
*const func
=
4859 rb_block_given_p() ? uniq_iter
: uniq_func
;
4861 hash
= rb_obj_hide(rb_hash_new());
4862 rb_block_call(obj
, id_each
, 0, 0, func
, hash
);
4863 ret
= rb_hash_values(hash
);
4864 rb_hash_clear(hash
);
4869 compact_i(RB_BLOCK_CALL_FUNC_ARGLIST(i
, ary
))
4874 rb_ary_push(ary
, i
);
4883 * Returns an array of all non-+nil+ elements:
4885 * a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil]
4886 * a.compact # => [0, "a", false, false, "a", 0]
4891 enum_compact(VALUE obj
)
4896 rb_block_call(obj
, id_each
, 0, 0, compact_i
, ary
);
4905 * \Module \Enumerable provides methods that are useful to a collection class for:
4907 * - {Querying}[rdoc-ref:Enumerable@Methods+for+Querying]
4908 * - {Fetching}[rdoc-ref:Enumerable@Methods+for+Fetching]
4909 * - {Searching and Filtering}[rdoc-ref:Enumerable@Methods+for+Searching+and+Filtering]
4910 * - {Sorting}[rdoc-ref:Enumerable@Methods+for+Sorting]
4911 * - {Iterating}[rdoc-ref:Enumerable@Methods+for+Iterating]
4912 * - {And more....}[rdoc-ref:Enumerable@Other+Methods]
4914 * === Methods for Querying
4916 * These methods return information about the \Enumerable other than the elements themselves:
4918 * - #include?, #member?: Returns +true+ if <tt>self == object</tt>, +false+ otherwise.
4919 * - #all?: Returns +true+ if all elements meet a specified criterion; +false+ otherwise.
4920 * - #any?: Returns +true+ if any element meets a specified criterion; +false+ otherwise.
4921 * - #none?: Returns +true+ if no element meets a specified criterion; +false+ otherwise.
4922 * - #one?: Returns +true+ if exactly one element meets a specified criterion; +false+ otherwise.
4923 * - #count: Returns the count of elements,
4924 * based on an argument or block criterion, if given.
4925 * - #tally: Returns a new Hash containing the counts of occurrences of each element.
4927 * === Methods for Fetching
4929 * These methods return entries from the \Enumerable, without modifying it:
4931 * <i>Leading, trailing, or all elements</i>:
4933 * - #entries, #to_a: Returns all elements.
4934 * - #first: Returns the first element or leading elements.
4935 * - #take: Returns a specified number of leading elements.
4936 * - #drop: Returns a specified number of trailing elements.
4937 * - #take_while: Returns leading elements as specified by the given block.
4938 * - #drop_while: Returns trailing elements as specified by the given block.
4940 * <i>Minimum and maximum value elements</i>:
4942 * - #min: Returns the elements whose values are smallest among the elements,
4943 * as determined by <tt><=></tt> or a given block.
4944 * - #max: Returns the elements whose values are largest among the elements,
4945 * as determined by <tt><=></tt> or a given block.
4946 * - #minmax: Returns a 2-element Array containing the smallest and largest elements.
4947 * - #min_by: Returns the smallest element, as determined by the given block.
4948 * - #max_by: Returns the largest element, as determined by the given block.
4949 * - #minmax_by: Returns the smallest and largest elements, as determined by the given block.
4951 * <i>Groups, slices, and partitions</i>:
4953 * - #group_by: Returns a Hash that partitions the elements into groups.
4954 * - #partition: Returns elements partitioned into two new Arrays, as determined by the given block.
4955 * - #slice_after: Returns a new Enumerator whose entries are a partition of +self+,
4956 * based either on a given +object+ or a given block.
4957 * - #slice_before: Returns a new Enumerator whose entries are a partition of +self+,
4958 * based either on a given +object+ or a given block.
4959 * - #slice_when: Returns a new Enumerator whose entries are a partition of +self+
4960 * based on the given block.
4961 * - #chunk: Returns elements organized into chunks as specified by the given block.
4962 * - #chunk_while: Returns elements organized into chunks as specified by the given block.
4964 * === Methods for Searching and Filtering
4966 * These methods return elements that meet a specified criterion:
4968 * - #find, #detect: Returns an element selected by the block.
4969 * - #find_all, #filter, #select: Returns elements selected by the block.
4970 * - #find_index: Returns the index of an element selected by a given object or block.
4971 * - #reject: Returns elements not rejected by the block.
4972 * - #uniq: Returns elements that are not duplicates.
4974 * === Methods for Sorting
4976 * These methods return elements in sorted order:
4978 * - #sort: Returns the elements, sorted by <tt><=></tt> or the given block.
4979 * - #sort_by: Returns the elements, sorted by the given block.
4981 * === Methods for Iterating
4983 * - #each_entry: Calls the block with each successive element
4984 * (slightly different from #each).
4985 * - #each_with_index: Calls the block with each successive element and its index.
4986 * - #each_with_object: Calls the block with each successive element and a given object.
4987 * - #each_slice: Calls the block with successive non-overlapping slices.
4988 * - #each_cons: Calls the block with successive overlapping slices.
4989 * (different from #each_slice).
4990 * - #reverse_each: Calls the block with each successive element, in reverse order.
4994 * - #map, #collect: Returns objects returned by the block.
4995 * - #filter_map: Returns truthy objects returned by the block.
4996 * - #flat_map, #collect_concat: Returns flattened objects returned by the block.
4997 * - #grep: Returns elements selected by a given object
4998 * or objects returned by a given block.
4999 * - #grep_v: Returns elements selected by a given object
5000 * or objects returned by a given block.
5001 * - #reduce, #inject: Returns the object formed by combining all elements.
5002 * - #sum: Returns the sum of the elements, using method <tt>+</tt>.
5003 * - #zip: Combines each element with elements from other enumerables;
5004 * returns the n-tuples or calls the block with each.
5005 * - #cycle: Calls the block with each element, cycling repeatedly.
5009 * To use module \Enumerable in a collection class:
5013 * include Enumerable
5015 * - Implement method <tt>#each</tt>
5016 * which must yield successive elements of the collection.
5017 * The method will be called by almost any \Enumerable method.
5022 * include Enumerable
5029 * Foo.new.each_entry{ |element| p element }
5037 * == \Enumerable in Ruby Classes
5039 * These Ruby core classes include (or extend) \Enumerable:
5051 * These Ruby standard library classes include \Enumerable:
5058 * Virtually all methods in \Enumerable call method +#each+ in the including class:
5060 * - <tt>Hash#each</tt> yields the next key-value pair as a 2-element Array.
5061 * - <tt>Struct#each</tt> yields the next name-value pair as a 2-element Array.
5062 * - For the other classes above, +#each+ yields the next object from the collection.
5064 * == About the Examples
5066 * The example code snippets for the \Enumerable methods:
5068 * - Always show the use of one or more Array-like classes (often Array itself).
5069 * - Sometimes show the use of a Hash-like class.
5070 * For some methods, though, the usage would not make sense,
5071 * and so it is not shown. Example: #tally would find exactly one of each Hash entry.
5076 Init_Enumerable(void)
5078 rb_mEnumerable
= rb_define_module("Enumerable");
5080 rb_define_method(rb_mEnumerable
, "to_a", enum_to_a
, -1);
5081 rb_define_method(rb_mEnumerable
, "entries", enum_to_a
, -1);
5082 rb_define_method(rb_mEnumerable
, "to_h", enum_to_h
, -1);
5084 rb_define_method(rb_mEnumerable
, "sort", enum_sort
, 0);
5085 rb_define_method(rb_mEnumerable
, "sort_by", enum_sort_by
, 0);
5086 rb_define_method(rb_mEnumerable
, "grep", enum_grep
, 1);
5087 rb_define_method(rb_mEnumerable
, "grep_v", enum_grep_v
, 1);
5088 rb_define_method(rb_mEnumerable
, "count", enum_count
, -1);
5089 rb_define_method(rb_mEnumerable
, "find", enum_find
, -1);
5090 rb_define_method(rb_mEnumerable
, "detect", enum_find
, -1);
5091 rb_define_method(rb_mEnumerable
, "find_index", enum_find_index
, -1);
5092 rb_define_method(rb_mEnumerable
, "find_all", enum_find_all
, 0);
5093 rb_define_method(rb_mEnumerable
, "select", enum_find_all
, 0);
5094 rb_define_method(rb_mEnumerable
, "filter", enum_find_all
, 0);
5095 rb_define_method(rb_mEnumerable
, "filter_map", enum_filter_map
, 0);
5096 rb_define_method(rb_mEnumerable
, "reject", enum_reject
, 0);
5097 rb_define_method(rb_mEnumerable
, "collect", enum_collect
, 0);
5098 rb_define_method(rb_mEnumerable
, "map", enum_collect
, 0);
5099 rb_define_method(rb_mEnumerable
, "flat_map", enum_flat_map
, 0);
5100 rb_define_method(rb_mEnumerable
, "collect_concat", enum_flat_map
, 0);
5101 rb_define_method(rb_mEnumerable
, "inject", enum_inject
, -1);
5102 rb_define_method(rb_mEnumerable
, "reduce", enum_inject
, -1);
5103 rb_define_method(rb_mEnumerable
, "partition", enum_partition
, 0);
5104 rb_define_method(rb_mEnumerable
, "group_by", enum_group_by
, 0);
5105 rb_define_method(rb_mEnumerable
, "tally", enum_tally
, -1);
5106 rb_define_method(rb_mEnumerable
, "first", enum_first
, -1);
5107 rb_define_method(rb_mEnumerable
, "all?", enum_all
, -1);
5108 rb_define_method(rb_mEnumerable
, "any?", enum_any
, -1);
5109 rb_define_method(rb_mEnumerable
, "one?", enum_one
, -1);
5110 rb_define_method(rb_mEnumerable
, "none?", enum_none
, -1);
5111 rb_define_method(rb_mEnumerable
, "min", enum_min
, -1);
5112 rb_define_method(rb_mEnumerable
, "max", enum_max
, -1);
5113 rb_define_method(rb_mEnumerable
, "minmax", enum_minmax
, 0);
5114 rb_define_method(rb_mEnumerable
, "min_by", enum_min_by
, -1);
5115 rb_define_method(rb_mEnumerable
, "max_by", enum_max_by
, -1);
5116 rb_define_method(rb_mEnumerable
, "minmax_by", enum_minmax_by
, 0);
5117 rb_define_method(rb_mEnumerable
, "member?", enum_member
, 1);
5118 rb_define_method(rb_mEnumerable
, "include?", enum_member
, 1);
5119 rb_define_method(rb_mEnumerable
, "each_with_index", enum_each_with_index
, -1);
5120 rb_define_method(rb_mEnumerable
, "reverse_each", enum_reverse_each
, -1);
5121 rb_define_method(rb_mEnumerable
, "each_entry", enum_each_entry
, -1);
5122 rb_define_method(rb_mEnumerable
, "each_slice", enum_each_slice
, 1);
5123 rb_define_method(rb_mEnumerable
, "each_cons", enum_each_cons
, 1);
5124 rb_define_method(rb_mEnumerable
, "each_with_object", enum_each_with_object
, 1);
5125 rb_define_method(rb_mEnumerable
, "zip", enum_zip
, -1);
5126 rb_define_method(rb_mEnumerable
, "take", enum_take
, 1);
5127 rb_define_method(rb_mEnumerable
, "take_while", enum_take_while
, 0);
5128 rb_define_method(rb_mEnumerable
, "drop", enum_drop
, 1);
5129 rb_define_method(rb_mEnumerable
, "drop_while", enum_drop_while
, 0);
5130 rb_define_method(rb_mEnumerable
, "cycle", enum_cycle
, -1);
5131 rb_define_method(rb_mEnumerable
, "chunk", enum_chunk
, 0);
5132 rb_define_method(rb_mEnumerable
, "slice_before", enum_slice_before
, -1);
5133 rb_define_method(rb_mEnumerable
, "slice_after", enum_slice_after
, -1);
5134 rb_define_method(rb_mEnumerable
, "slice_when", enum_slice_when
, 0);
5135 rb_define_method(rb_mEnumerable
, "chunk_while", enum_chunk_while
, 0);
5136 rb_define_method(rb_mEnumerable
, "sum", enum_sum
, -1);
5137 rb_define_method(rb_mEnumerable
, "uniq", enum_uniq
, 0);
5138 rb_define_method(rb_mEnumerable
, "compact", enum_compact
, 0);
5140 id__alone
= rb_intern_const("_alone");
5141 id__separator
= rb_intern_const("_separator");
5142 id_chunk_categorize
= rb_intern_const("chunk_categorize");
5143 id_chunk_enumerable
= rb_intern_const("chunk_enumerable");
5144 id_next
= rb_intern_const("next");
5145 id_sliceafter_enum
= rb_intern_const("sliceafter_enum");
5146 id_sliceafter_pat
= rb_intern_const("sliceafter_pat");
5147 id_sliceafter_pred
= rb_intern_const("sliceafter_pred");
5148 id_slicebefore_enumerable
= rb_intern_const("slicebefore_enumerable");
5149 id_slicebefore_sep_pat
= rb_intern_const("slicebefore_sep_pat");
5150 id_slicebefore_sep_pred
= rb_intern_const("slicebefore_sep_pred");
5151 id_slicewhen_enum
= rb_intern_const("slicewhen_enum");
5152 id_slicewhen_inverted
= rb_intern_const("slicewhen_inverted");
5153 id_slicewhen_pred
= rb_intern_const("slicewhen_pred");