Files and Directories
Read File
Ruby can read text from a file after another part of the program creates it.
Read File
read_file.rb
require "tmpdir"
line =
Dir.mktmpdir do |dir|
path = File.join(dir, "notes.txt")
File.write(path, "#{line}\nsecond\n")
content = File.read(path)
rows = content.split("\n")
puts "file=#{File.basename(path)}"
puts "first=#{rows.first}"
puts "line_count=#{rows.length}"
end
require "tmpdir"
line =
Dir.mktmpdir do |dir|
path = File.join(dir, "notes.txt")
File.write(path, "#{line}\nsecond\n")
content = File.read(path)
rows = content.split("\n")
puts "file=#{File.basename(path)}"
puts "first=#{rows.first}"
puts "line_count=#{rows.length}"
end
require "tmpdir"
line =
Dir.mktmpdir do |dir|
path = File.join(dir, "notes.txt")
File.write(path, "#{line}\nsecond\n")
content = File.read(path)
rows = content.split("\n")
puts "file=#{File.basename(path)}"
puts "first=#{rows.first}"
puts "line_count=#{rows.length}"
end
file read
`File.read` loads the whole file content as a string.