View Category

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read
clojure
(slurp "/tmp/foobar")

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}
}
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
clojure
(with-out-writer "output.txt" (println "Hello file!"))

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (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')
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))