shou2017.com
JP

Ruby Certification: File.open Method

Thu Aug 16, 2018
Sat Aug 10, 2024

This is a summary of the modes for the File.open method, which frequently appears in the Ruby Silver exam.

Mode Description
“r” Read mode. This is the default if no argument is specified.
“w” Write mode. If the file exists, its contents are cleared.
“a” Append mode. Always appends to the end of the file.
“r+” Read-write mode. The read/write position starts at the beginning.
“w+” Read-write mode. Similar to r+, but clears the file contents if it exists.
“a+” Read-write mode. The read position starts at the beginning, but writes always append to the end.
<!-- Sample file: sample.md -->

Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.

Examples for r and r+

r

Read mode. This is the default if no argument is specified.

file = File.open("sample.md") # "r" is the default, so it can be omitted
puts file.read
file.close

=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.

r+

Read-write mode. The read/write position starts at the beginning.

file = File.open("sample.md", "r+")
file.puts("My Diary")
file.close

=>
My Diary

An open-source dynamic programming language focused on simplicity and productivity.

Examples for w and w+

w

Write mode. If the file exists, its contents are cleared.

file = File.open("sample.md", "w")
file.puts("My Diary")
file.close

=>
My Diary

w+

Read-write mode. Similar to r+, but clears the file contents if it exists.

file = File.open("sample.md", "w+")
file.puts("My Diary")
file.close

=>
My Diary

Examples for a and a+

a

Append mode. Always appends to the end of the file.

file = File.open("sample.md", "a")
file.puts("My Diary")
file.close

=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
My Diary

a+

Read-write mode. The read position starts at the beginning, but writes always append to the end.

file = File.open("sample.md", "a+")
file.puts("My Diary")
file.close

=>
Ruby is...
An open-source dynamic programming language focused on simplicity and productivity.
My Diary

Reference

プロを目指す人のためのRuby入門[改訂2版] 言語仕様からテスト駆動開発・デバッグ技法まで

See Also