I,
Create a file
F = file. new (file. join ("C:", "test.txt"), "W +") F. puts ("I am Jack") F. puts ("Hello World ")
File Mode
"R": Read-Only. Starts at beginning of file (default mode ).
"R +": Read-write. Starts at beginning of file.
"W": Write-only. truncates existing file to zero length or creates a new file for writing.
"W +": Read-write. truncates existing file to zero length or creates a new file for reading and writing.
"": Write-only. Starts at end of file if file exists; otherwise, creates a new file for writing.
"A +": Read-write. Starts at end of file if file exists; otherwise, creates a new file for reading and writing.
"B":( DOS/Windows only.) binary file mode. may appear with any of the key letters listed above
Ii. Reading files
File = file. open (file. join ("C:", "test.txt"), "R") file. each {| Line | print "# {file. lineno }. ", line} file. close
Output:
1. Complete the rest of the mountains on the day
2. Yellow River Current
3. Thousands of miles away
4. Next floor
3. Create, delete, and rename an object
File. New ("books.txt", "W") file. Rename ("books.txt", "chaps.txt") file. Delete ("chaps.txt ")
Iii. Directory operations
Create directory dir. mkdir ("C:/testdir") # Delete the directory dir. rmdir ("C:/testdir") # query the files in the directory P dir. entries (file. join ("C:", "Ruby ")). join ('') # traverse the directory dir. entries (file. join ("C:", "Ruby ")). each {| E | puts e}
Output:
"C:/studyruby" "C:/ruby"
View directory information
D: \ study \ rubysample> irbirb (main): 001: 0> dir = dir. open (file. join ("C:", "Ruby") = ># IRB (main): 002: 0> dir. path => "C:/ruby" IRB (main): 003: 0> dir. tell => 0irb (main): 004: 0> dir. read => ". "IRB (main): 005: 0> dir. rewind => # IRB (main): 006: 0> dir. each {| E | puts outputs ==># IRB (main): 007: 0>