aboutsummaryrefslogtreecommitdiffstats
path: root/enumerator.c
diff options
context:
space:
mode:
authorzverok <zverok.offline@gmail.com>2019-10-26 14:02:59 +0300
committerNobuyoshi Nakada <nobu@ruby-lang.org>2019-10-27 18:57:39 +0900
commit417369e0cd6ec96950d2d48f2c94e7b1eb012076 (patch)
tree9e3a5ff0c1a3ffd5cbfb797638454b2cee4ae6c7 /enumerator.c
parentaba23d83f2697247488a2e770fcb9ce5abfcd16c (diff)
downloadruby-417369e0cd6ec96950d2d48f2c94e7b1eb012076.tar.gz
Improve Enumerator.produce docs
* Add to NEWS; * Add examples of while-alike cycles with practical tasks.
Diffstat (limited to 'enumerator.c')
-rw-r--r--enumerator.c15
1 files changed, 15 insertions, 0 deletions
diff --git a/enumerator.c b/enumerator.c
index eee3a34e6b..06e2a9e6a7 100644
--- a/enumerator.c
+++ b/enumerator.c
@@ -2923,6 +2923,21 @@ producer_size(VALUE obj, VALUE args, VALUE eobj)
*
* ancestors = Enumerator.produce(node) { |prev| node = prev.parent or raise StopIteration }
* enclosing_section = ancestors.find { |n| n.type == :section }
+ *
+ * Using ::produce together with Enumerable methods like Enumerable#detect,
+ * Enumerable#slice, Enumerable#take_while can provide Enumerator-based alternative
+ * for +while+ and +until+ cycles:
+ *
+ * # Find next Tuesday
+ * require 'date'
+ * Enumerator.produce(Date.today, &:succ).detect(&:tuesday?)
+ *
+ * # Simple lexer:
+ * require 'strscan'
+ * scanner = StringScanner.new('7+38/6')
+ * PATTERN = %r{\d+|[-/+*]}
+ * p Enumerator.produce { scanner.scan(PATTERN) }.slice_after { scanner.eos? }.first
+ * # => ["7", "+", "38", "/", "6"]
*/
static VALUE
enumerator_s_produce(int argc, VALUE *argv, VALUE klass)