Iterable
Abstract type for iterable values. Values that implement the (iter) protocol
are instances of Iterable, which can be used for type testing.
Iterable is not constructible directly.
Methods
iter
Returns an iterator over the value.
Returns
Forwarded methods
x.foo(...) on an Iterable means x.iter().foo(...), so most of
Iter's methods can be called on a container directly:
assert_eq [...[1, 2, 3].map (do |x| x * 2)] [2, 4, 6]
assert_eq ([1, 2, 3].fold 0 (do |acc x| acc + x)) 6
| Method | Description |
|---|---|
all pred? |
Whether every item is truthy |
any pred? |
Whether any item is truthy |
fold init func |
Accumulates a value over the items |
map func |
Transforms each item |
filter pred |
Keeps items for which pred is truthy |
chain ...values |
Concatenates with further iterables |
zip ...values |
Pairs items with those of further iterables |
take n |
Yields at most the first n items |
skip n |
Discards the first n items |
enumerate |
Pairs each item with its index |
find pred |
First item for which pred is truthy |
min :default? |
Smallest item |
max :default? |
Largest item |
Three of Iter's methods are deliberately not forwarded, and raise
FieldError on a container:
nextis stateful. A container has no iteration position of its own, so each call would mint a fresh iterator and a loop overnextwould keep returning the first item.countwould be an O(n) way to ask for what most containers answer in constant time withlen.Dictalso definescountwith an unrelated meaning.kvdescribes the pair shape of an iterator; how a value spreads is the iterable's own business.
Call iter explicitly to reach any of them: