Hacker News new | comments | show | ask | jobs | submit login

Pretty sure Ruby has this.

File.open(name, mode) receives a block, executes it, and then closes the file.




Ruby 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.


You 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).


Having 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.




Applications are open for YC Winter 2019

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: