Files and IO

Contents
Read a whole file
Iterate lines
Write files
List a directory

Read a whole file

The method File.read loads a whole file into one string, which suits small configs and study scripts. Reading huge logs this way can exhaust memory, so treat it as the small file tool. The script below reads its own source file, so it runs in any folder.

text = File.read(__FILE__) puts text.empty?

false

Iterate lines

The iterator File.foreach yields each line in turn while keeping memory flat. Every line keeps its trailing newline, and chomp trims it away. Prefer this form for logs and dumps of unknown size.

File.write("demo.txt", "a\nb\n") File.foreach("demo.txt") do |line| puts line.chomp end

a
b

Write files

The method File.write replaces the whole file content with the given string. Opening with mode w in a block serves several writes in one session. Newlines never appear on their own: every line break comes from the strings you pass.

File.write("demo.txt", "hello") puts File.read("demo.txt")

hello

List a directory

The method Dir.children lists the names inside a folder. The predicate Dir.exist? checks that a folder is present before touching it. The method File.join assembles folder and file names into a correct path on any system.

names = Dir.children(".") puts names.is_a?(Array) puts Dir.exist?(".")

true
true

Next: Exceptions

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: