Files and IO Flashcards
What is the standard subclass of IO?
File class
What are the Socket library subclasses from IO?
TCPSocket or UDPSocket
Which extension provides methods for interacting with the console?
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console
Name some IO console methods?
io/console have the following methods:
IO::console IO#raw,IO#raw! IO#cooked,IO#cooked! IO#getch IO#echo=,IO#echo? IO#noecho IO#winsize,IO#winsize= IO#iflush IO#ioflush IO#oflush Example require 'io/console' rows, columns = $stdout.winsize puts "Your screen is #{columns} wide and #{rows} tall"
How can you open the file using File class?
There are two methods to open a file in Ruby:
File.new method : Using this method a new file can be created for reading, writing or both.
File.open method : Using this method a new file object is created. That file object is assigned to a file.
Difference between both the methods is that File.open method can be associated with a block while File.new method can’t.
Syntax:
f = File.new(“fileName.rb”)
Or,
File.open(“fileName.rb”, “mode”) do |f|
What are the ways to read a file using File class?
There are three different methods to read a file.
To return a single line, following syntax is used.
Syntax: f.gets
code…
To return the whole file after the current position, following syntax is used.
Syntax: f.read
code…
To return file as an array of lines, following syntax is used.
Syntax: f.readlines
[code…]
Explain sysread method?
The sysread method is also used to read the content of a file. With the help of this method you can open a file in any mode.
aFile = File.new("about.txt", "r") if aFile content = aFile.sysread(40) puts content end
Explain syswrite method?
With the help of syswrite method, you can write content into a file. File needs to be opened in write mode for this method.
aFile = File.new(“about.txt”, “r+”)
if aFile
aFile.syswrite(“New content is written in this file.\n”)
end
What are the following open mode implies?
w+
r+
a+
“w+” Read-write, truncates existing file to zero length
or creates a new file for reading and writing.
“r+” Read-write, starts at beginning of file.
“a+” Read-write, each write call appends data at end of file.
Creates a new file for reading and writing if file does
not exist.
Explain STDIN,STDOUT,STDERR?
Ruby IO objects wrap Input/Output streams. The constants STDIN, STDOUT, and STDERR point to IO objects wrapping the standard streams. By default the global variables
$stdin,
$stdout, and
$stderr point to their respective constants.
$stdin is read-only while $stdout and $stderr are write-only.