Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #6939
| From | Robert Klemme <shortcutter@googlemail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Enumerators == Resource Leak Risk? |
| Date | 2014-03-26 22:28 +0100 |
| Message-ID | <bpgv48Fms4cU1@mid.individual.net> (permalink) |
| References | <c1d4bed1-7b7b-4920-8f86-3afa6a733214@googlegroups.com> |
On 21.03.2014 22:26, keithrbennett@gmail.com wrote:
> I've recently been writing custom Enumerable classes, and thought it
> would be a good idea to support Enumerators as well. Making an
> Enumerable Enumerator-enabled seems to be as simple as adding the
> following line to the beginning of each():
>
> return to_enum unless block_given?
>
> However, I realized that I might be introducing a risk of resource
> leaks by doing so. For example, if my enumerable opens a file to read
> from, and I read a few but not all values from an enumerator it gives
> me, then the Enumerable's each() method that feeds Enumerator's next
> method never completes, and the file close there is never executed.
>
> Should I *not* support enumerators if this is the case?
> Any insight as to the best way to handle this?
No idea whether it's the best approach but you could remove / invalidate
all methods which do not use each semantic on the returned Enumerator,
e.g. :feed, :inspect, :next, :next_values, :peek, :peek_values, :rewind
Personally I believe the external iteration functionality should be
separated from the "regular" internal iteration functionality. That way
a clean separation would be achieved. For me the biggest value in
to_enum lies in the fact that I can turn any method into an iteration,
e.g. by doing things like 5.times.map {|x| x * 2}. I cannot remember
having felt the need for external iteration and if so I would not have
minded to make it explicit.
Kind regards
robert
Back to comp.lang.ruby | Previous | Next — Previous in thread | Find similar
Enumerators == Resource Leak Risk? keithrbennett@gmail.com - 2014-03-21 14:26 -0700 Re: Enumerators == Resource Leak Risk? Robert Klemme <shortcutter@googlemail.com> - 2014-03-26 22:28 +0100
csiph-web