Read/Write File in Ruby
Simplest form of full Read / Write for a file in Ruby:
puts File.read(file_name)
File.write('/path/to/file', 'Some glorious content')
Line by Line Read
- Why is “slurping” a file not a good practice? Slurping may be acceptable for configuration files, but slurping an input file makes the program practically useless for pipelines.
IO.foreach("testfile") {|x| print "GOT ", x }
File.foreach('testfile') {|x| print "GOT", x }
Block API
File::open('yozloy.txt','w') do |f|
f << 'Some contains'
end
see also
Written on August 29, 2018, Last update on August 16, 2021
file
ruby