How to write to file in Ruby?
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.
Thanks, I too was looking for a solution. This is really very helpful for me.
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"
.
The formatting tools on this editor appear to be insufficient to format nested quotes and preformatted ri output.
I’m not sure if this method exists. Which Ruby version are you using?
:~$ ri File.each_line
produces:
= File.each_line`
( from ruby core)
=== Implementation from IO`
each_line(*args)
Executes the block for every line in ios, where lines are
separated by sep. ios must be opened for reading or an
IOError will be raised.
If no block is given, an enumerator is returned instead.
`File#each_line` is actually an alias `for File#each`