Ruby Basic File Read and Write

| Comments

Read text file with one line: absolute_filename, "rb"){ |f| @contents = }

Write text with one line : absolute_filename, "w" ){ |f| f.write @contents }

Explanation and other ways

When reading a text file in the open command rb implies ‘read binary’ mode which creates the .read method for the entire file. The following line looks simpler but the file object in not closed. If a block is passed { |io| block } then the File is closed after the block completes.

@contents = absolute_filename, "rb").read

That should could be broken into 3 lines so that the file object can be closed. This is equivalent to the first one line example.

f = absolute_filename, "rb")
@contents =

The File will be automatically closed when program quits but if you create a long life process with hundreds of files not closing might cause performance issues.

Line by Line read, block containd with do end

@contents = '' absolute_filename, "r") do |f|
  f.each_line do |line|
    @contents += line

Write file, with explicit close.

f = absolute_filename, "w" )
f.write @contents