开发者

Do I need to close the file when using YAML::load?

like the following line of code

开发者_如何转开发
sites = YAML::load(File.open(SITESPATH))

is it necessary to change to

File.open(SITESPATH) do |file|
  sites = YAML::load(file)
end

just in order to make it sure that file got closed?


Yes, you should close the file, so your second example is the correct one.

Just as a side-note, remember that the sites variable will not be visible outside the block, unless you already created it before the block.

Because IO.open, when called with block, returns the value of the block, you may use:

sites = File.open(SITESPATH) {|file| YAML::load(file) }


You could use YAML.load_file(filename) instead.


This isn't really about YAML::load so much as it is about File/IO streams generally.

Called without a block, File.open is exactly the same as File.new. This doesn't close a file on its own, so you would need to close it yourself.

From the documentation:

With no associated block, [File.]open is a synonym for IO.new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO.open returns the value of the block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜