instance method
Enumerable#lazy
() -> ::Enumerator::Lazy[Elem]
e.lazy → lazy_enumerator
enumerator.c
View on GitHub ↗
static VALUE
enumerable_lazy(VALUE obj)
{
VALUE result = lazy_to_enum_i(obj, sym_each, 0, 0, lazyenum_size, rb_keyword_given_p());
/* Qfalse indicates that the Enumerator::Lazy has no method name */
rb_ivar_set(result, id_method, Qfalse);
return result;
}
Returns an Enumerator::Lazy, which redefines most Enumerable methods to postpone enumeration and enumerate values only on an as-needed basis.
Example
The following program finds pythagorean triples:
Example
def pythagorean_triples (1..Float::INFINITY).lazy.flat_map {|z| (1..z).flat_map {|x| (x..z).select {|y| x**2 + y**2 == z**2 }.map {|y| [x, y, z] } } } end # show first ten pythagorean triples p pythagorean_triples.take(10).force # take is lazy, so force is needed p pythagorean_triples.first(10) # first is eager # show pythagorean triples less than 100 p pythagorean_triples.take_while { |*, z| z < 100 }.force