Reputation: 125
Why does this not work in Ruby when reading and writing to files?
def write_to_file(a_file)
a_file.puts("hello")
end
a_file = File.new("test.txt", "w")
write_to_file(a_file)
the alternative i have found is to pass the file name to each function that reads or writes from it, and open and close it in that function.
why can't i open the file and pass that open file object to a function? does the a_file
variable I am assigning not create a file object?
Upvotes: 0
Views: 291
Reputation: 101891
File.new
does create a file but its opened in buffered mode (or non-sync mode), unless filename is a tty. If you want to open a file and write contents to it the idiomatic way is:
File.open("test.txt", "w") do |file|
file.write("hello")
end
This ensures that the file is closed when you're finished. That file handler can be passed around however you want:
def write_to_file(file)
file.write("hello")
end
File.open("test.txt", "w") do |file|
write_to_file(file)
end
Upvotes: 2