4 ms·
In ruby you can create a file pointer as a lexically scoped object: def write(something) f = File.open("/path/to/somewhere", "w+") f << something e
by grandalf 17y ago
In ruby you can create a file pointer as a lexically scoped object:
def write(something)
f = File.open("/path/to/somewhere", "w+")
f << something
end
The variable f is local to the write method. Without explicitly closing the file, it may not be flushed to disk until the ojbect is garbage collected (I think).
- kscaldef 17y agoThat delay until the next garbage collection is a big caveat. While you might get away with this for file handles in some situations (honestly, I'm not sure that File#close really guarantees a write to disk anyway), it makes this technique essentially useless for mutexes. (Edit: I should also point out that that's a function-scoped variable, not a lexically-scoped variable. Ruby doesn't have lexically-scoped variables.)
- aaronblohowiak 17y agoFile.open('path', 'w') do |f| f << something end will do what you want
- kscaldef 17y agoIt might be good to read the whole discussion, particularly noting what I personally have said, before making conclusions about what I want.
- aaronblohowiak 17y agoI should have simply explained that my example will close the file handle and flush the changes out at the end of the block passed to the anonymous file handle, instead of making a statement about your wants.