writing to a file in ruby

In a recent interview I was asked how to perform certain actions, like how to combine two arrays, use #concat. I was able to answer most of the questions, except how to write to a file. I had never done this, and could not even think of a way to do it.

If we wanted to add some text to a .txt file, the Ruby File class has handy methods to do this. Within a Ruby file, simply type the following and the newly created sample.txt file will have the “Hello, world.” text.

File.open(‘example.txt’, ‘w’) do |f|
f.puts “Hello, world.”

Of course this can be refactored to look more pleasing.

File.open('example.txt', 'w') { |f|  f.puts "Hello, world." }

The #open method, from the File class, requires two arguments

  • a filename
  • the read/write mode

If the file being written to does not exist, it will be created. However, using ‘w’ mode, which stands for ‘write’, on a file that exits will overwrite that file. To append to an existing file, use ‘a’ as the mode.

Like what you read? Give david weinstein a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.