3 ms·
It creates an Enumerator (for practical purposes consider it a continuation) over the method "each" unless you've passed in an argument named "block", which by
by vidarh 6y ago
It creates an Enumerator (for practical purposes consider it a continuation) over the method "each" unless you've passed in an argument named "block", which by convention would be a block argument (a closure passed after the argument list effectively) that will evaluate to Proc object.
Consider this example:
class Foo
def each
yield(42)
yield(:hello)
yield(:world)
end
end
You can now do:
Foo.new.to_enum(:each)
(In this case the ":each" is redundant - to_enum defaults to :each, so you could do Foo.new.to_enum)
And you will get back an Enumerator that supports the Enumerable interface, giving you methods like map, inject, to_a (to array) etc. as a facade to the original object so you can do (for example:
Foo.new.to_enum.to_a
=> [42, :hello, :world]
(you can achieve a similar thing by including Enumerable into the class in question, but to_enum lets you do this on arbitrary objects without messing around with the class)
It allows any method to return something that behaves like a collection class without needing to pass more than a method that implements "each" by yielding each value of the collection.
You can also do this with a bare lambda, btw., but the syntax is a bit awkward as "yield" is syntactic sugar over calling the "call" method over an implicit (unnamed) block argument that isn't quite as transparent as you might like:
ob = ->(&block) { block.call(42); block.call(:hello); block.call(:world) }.to_enum(:call)
The explicit "&block" argument is needed because "yield" has lexical scope where defined.
"ob" is now an enumerator that supporters each, to_a, map etc.:
ob.to_a
=> [42, :hello, :world]
- DarkWiiPlayer 6y ago> for practical purposes consider it a continuation But it's not though. While coroutines can be used to implement one-shot continuations and vice versa, they are very different features and behave completely differently.
- vidarh 6y agoWhile you're technically right, in terms of using it as a shortcut to give superficial understanding of how Enumerator functions the distinctions are largely irrelevant.