How to write to file in Ruby?

How to write to file in Ruby?

1 Like

The simplest way to write to a file in Ruby is to use the write method:

File.write('hello.txt', 'Hello, world!')

If you need to append to a file (add new data to the end of the file), you can use the append method:

File.append('hello.txt', 'Hello, world!')

If you need to read from a file, you can use the read method:

File.read('hello.txt') # => "Hello, world!"

If you need to read from a file line by line, you can use the each_line method:

File.each_line('hello.txt') do |line|
  puts line
end

This will print each line of the file to the console.

1 Like

Thanks, I too was looking for a solution. This is really very helpful for me.

  1. Open the file in write mode (“w” flag)
  2. Use the write method to add data to the file.
  3. If you didn’t use the block version, remember to close.
    what makes a good fillet knife
File.append?

Are you sure?

Use this instead:

File.open('hello.txt', 'a') { |f| f.write('appended data!') }

I’m not sure if this method exists. Which Ruby version are you using?

I’d use File.foreach('hello.txt').each { |x| puts x } to read files and print line by line. Note that even if your file is 4 GB, it will only load the first line, no matter what the size is. If your first line is 4 GB, it will consume 4 GB memory at once! Use File.open('hello.txt','r').readpartial(500) to read 500 bytes from hello.txt.

There’s also IO.foreach(), but don’t use this because user’s can pipe to it. For example: IO.foreach('|whoami').first #=> "sourav\n".

1 Like