3 ms·
Pretty sure Ruby has this. File.open(name, mode) receives a block, executes it, and then closes the file.
by tkahn6 15y ago
Pretty sure Ruby has this.
File.open(name, mode) receives a block, executes it, and then closes the file.
- silentbicycle 15y agoRuby has a specific instance of that pattern, but to my knowledge it lacks a way to say, "do some arbitrary operation that has a side-effect, do this, then undo the operation". The function taking the block still has special-case code to open and close files.
- skrebbel 15y agoYou still have to implement the inverse of the arbitrary operation, at some point, somehow. A programming language can't figure out what the inverse of open() is without someone somewhere telling it to close(). The point of the idiom is to have a library figure that out so that users don't have to. Therefore, Ruby supports it fully (there where API developers are sane, that is).
- silentbicycle 15y agoHaving that built in for every side-effect in the language is pretty amazing, though. Case by case, the block scoping idiom is a good way to handle it.