Ruby's input and output operations. Is input to read data from the keyboard, files or other programs. Generating a data output program. Can be output to screen, file or other programs.
Ruby some methods of classes & performs input and output operations. For example Kernel, IO, Dir or File. Important to note Kernal, IO, two different ways
Output to the terminal
Ruby has some methods printout on the terminal. Such methods are part of Kernel module. Kernel module method is valid for all Ruby objects.
print and puts methods the text is output to the terminal. The difference is that they will add a line break at the end. print actual call object to_s method, puts a line break will be added later
Further there are three output Ruby methods. printf, p, putc
p “Lemon” p会调用对象的inspect方法。这个方法对于调试很有用。
printf “There are %d apples\n”, 3 printf方法因C语言而出名。它能够将字符串格式化。
putc ‘K’putc方法在终端上打印一个字符
Input from the terminal
Typically read the data from the terminal using gets method. chomp method. It is a string method for removing the blank end of the string. When we perform an input operation it useful. This method name and usage from the Perl language.
#!/usr/bin/ruby
print “Enter a string: “
inp = gets.chomp
puts “The string has #{inp.size} characters”
file
We know that the official documentation from Ruby IO class is the base class for all inputs and outputs. File class only IO a subclass of class. These two classes are closely related.
#!/usr/bin/ruby
f = File.open(‘output.txt’, ‘w’)
f.puts “The Ruby tutorial”
f.close