View Category

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
IO.write("file.txt", "some text that overwrites")

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}

Process each file in a directory recursively

ruby
def procdir(dirname)
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end

# ------

procdir('/tmp')