0

Just some food for thought about how necessary it is to close the files that I opened explicitly in the code. I came from a background of programming in C and C++, and starting to navigate my way through Ruby. Thanks in advance for your feedback.

from_file, to_file = ARGV
script = $0

puts "Copying from #{from_file} to #{to_file}"
File.open(to_file, 'w').write(File.open(from_file).read())

puts "Alright, all done."
stanigator
  • 10,768
  • 34
  • 94
  • 129

4 Answers4

7

Not closing files is always bad practice unless you are using something like the with statement in python.

While a scripting language will usually close open files on exit, it's cleaner to do it as soon as you are done with the file - especially when writing to it.

Apparently Ruby has something similar to python's with:

File.open(from_file, 'r') do |f_in|
    File.open(to_file, 'w') do |f_out|
        f_out.write(f_in.read)
    end
end

Relevant docs: http://ruby-doc.org/core-1.9.3/File.html#method-c-open

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • That would mean I would need extra lines to grab the handles though. Or does it? – stanigator May 10 '12 at 06:40
  • 4
    @stanigator: Why do you care (even a little bit) about adding a couple lines of code if that increases the quality of your code? – mu is too short May 10 '12 at 06:46
  • Besides that, I'm sure ruby has a simple method to copy a file that does not involve you opening either of the files manually. – ThiefMaster May 10 '12 at 06:47
  • @ThiefMaster: I guess I'll find out in the next few days. Do both `do` in Ruby and `with` in Python allow garbage collection with the file i/o to take place automatically when the code hits `end`? I'm not familiar with Python either, and it's next on my learning bucket list after Ruby. – stanigator May 10 '12 at 06:48
  • 2
    @stanigator No, the `do...end` here is a *block* that is passed to the `open` method, which then opens the file, then runs the block passing the file as an argument, and when the block finishes running it then closes the file. – Andrew Marshall May 10 '12 at 06:56
  • @AndrewMarshall: Thanks for the complete explanation. My guess only hit the part of when the files are closed. – stanigator May 10 '12 at 06:57
2

Here's a shorter version:

File.write to_file, File.read(from_file)
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
1

This code (Matheus Moreira) closes files automatically:

File.write to_file, File.read(from_file)

There are no ways to close files in this code:

File.open(to_file, 'w').write(File.open(from_file).read())

I guess automatically closing too.

Andrew
  • 51
  • 1
  • 5
0

It's a good answer but it's more 'ruby' to put the output file on the outer block and use << :

File.open(to_file, 'w') do |f_out|
  f_out << File.open(from_file){|f| f.read}
end

note how you do not need the 'r' when reading.

pguardiario
  • 53,827
  • 19
  • 119
  • 159