Too many return-statements = bad style?

Michael Geary Mike at Geary.com
Thu Jul 15 01:26:35 EDT 2004


> Michael Geary wrote:
> > The Ruby code always closes the file when the code block (the
> > loop body) exits, even if the code block raises an exception. So,
> > the Ruby code:
>
> File.open(...).each do |line|
>     [ process line from file ]
> end
>
> is a closer match to this Python code:
>
> f = file(...)
> try:
>     for line in f:
>         [ process line from file ]
> finally:
>     f.close()

Steve Lamb wrote:
> Kinda breaks that whole explicit is better than implicit rule, don't it.

One of the most fundamental idioms in Ruby is to acquire a resource, pass it
into a code block, and release the resource when the code block exits. It's
essentially Ruby's version of the RAII design pattern, which is widely
considered to be a Good Thing because it insures that the resource is
released properly.

It's also closely related to Python's generator functions, which work very
much like the Ruby functions that accept code blocks.

But I'm embarrassed to admit I got the Ruby code wrong. The version I posted
doesn't close the file after the block as I said. That only happens if you
give File.open() itself the code block, like this:

File.open(...) do |file|
    file.each do |line|
        [ process line from file ]
    end
end

I *think* I got it right this time, anyway. That's what I get for posting
code in a language I'm just beginning to learn. :-)

> What happens if I don't want the file closed at the end of the loop?
> I'm guessing I have to start fighting with the language.

Not at all. You just don't give File.open a code block. You're always free
to write code like this:

file = File.open(...)
[do stuff with file]
file.close

-Mike





More information about the Python-list mailing list