2014年11月2日 星期日

[ 文章收集 ] Input & output in Ruby

Source From Here 
Preface 
In this part of the Ruby tutorial, we will talk about input & output operations in Ruby. Input is any data that is read by the program, either from a keyboard, file or other programs. Output is data that is produced by the program. The output may go to the screen, to a file or to another program. 

Input & output is a large topic. We bring forward some examples to give you a general idea of the subject. Several classes in Ruby have methods for doing input & output operations. For example KernelIODir or File

Writing to console 
Ruby has several methods for printing output on the console. These methods are part of the Kernel module. Methods of the Kernel are available to all objects in Ruby. 
  1. #!/usr/bin/ruby  
  2.   
  3. print "Apple "  
  4. print "Apple\n"  
  5.   
  6. puts "Orange"  
  7. puts "Orange"  
The print method prints two consecutive "Apple" strings to the terminal. If we want to create a new line, we must explicitly include a newline character. The newline character is \n. Behind the scenes, the print method actually calls the to_s method of the object being printed; The puts method prints two strings to the console. Each is on its own line. The method includes automatically the newline character. 

According to the Ruby documentation, the print method is an equivalent to the $stdout.print. The $stdout is a global variable which holds the standard output stream. 
  1. #!/usr/bin/ruby  
  2.   
  3. $stdout.print "Ruby language\n"  
  4. $stdout.puts "Python language"  
Ruby has another three methods for printing output. 
  1. #!/usr/bin/ruby  
  2.   
  3. "Lemon"  
  4. "Lemon"  
  5.   
  6. printf "There are %d apples\n"3  
  7.   
  8. putc 'K'  
  9. putc 0xA  
The p calls the inspect method upon the object being printed. The method is useful for debugging; The printf method is well known from the C programming language. It enables string formatting; The putc method prints one character to the console. Printing data to the console using the kernel methods is a shortcut: a convenient way to print data. The following example shows a more formal way to print data to the terminal. 
  1. ios = IO.new STDOUT.fileno  
  2. ios.write "ZetCode\n"  
  3. ios.close  
The new method returns a stream to which we can write data. The method takes a numeric file descriptor. The STDOUT.fileno gives us the file descriptor for the standard output stream. On Unix systems the standard terminal output is connected to a special file called /dev/tty. By opening it and writing to it, we write to a console. 
  1. #!/usr/bin/ruby  
  2.   
  3. fd = IO.sysopen "/dev/tty""w"  
  4. ios = IO.new(fd, "w")  
  5. ios.puts "ZetCode"  
  6. ios.close  
The sysopen method opens the given path, returning the underlying file descriptor number. 

Reading input from console 
The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. 
  1. #!/usr/bin/ruby  
  2.   
  3. inp = $stdin.read  
  4. puts inp  
The read method reads data from the standard input until it reaches the end of the file. EOF is produced by pressing Ctrl+D on Unix or Ctrl+Z on Windows. 

The common way to read data from the console is to use the gets method. 
  1. #!/usr/bin/ruby  
  2.   
  3. print "Enter your name: "  
  4. name = gets  
  5. puts "Hello #{name}"  

To remove the newline character, we can use chomp method. 

Files 
From the official Ruby documentation we learn that the IO class is the basis for all input and output in Ruby. The File class is the only subclass of the IO class. The two classes are closely related. In the first example, we open a file and write some data to it: 
  1. #!/usr/bin/ruby  
  2.   
  3. f = File.open('output.txt''w')  
  4. f.puts "The Ruby tutorial"  
  5. f.close  
We will have a similar example which will show additional methods in action. 
  1. #!/usr/bin/ruby  
  2.   
  3. File.open('langs''w'do |f|     
  4.     f.puts "Ruby"  
  5.     f.write "Java\n"  
  6.     f << "Python\n"      
  7. end  
If there is a block after the open method then Ruby passes the opened stream to this block. At the end of the block, the file is automatically closed. In the next example, we show a few methods of the File class. (mtime: Returns the modification time for the named file as a Time object.
  1. #!/usr/bin/ruby  
  2.   
  3. puts File.exists? 'tempfile'  
  4.   
  5. f = File.new 'tempfile''w'  
  6. puts File.mtime 'tempfile'  
  7. puts f.size  
  8.   
  9. File.rename 'tempfile''tempfile2'  
  10.   
  11. f.close  
Next, we will be reading data from the files on the disk. 
  1. #!/usr/bin/ruby  
  2.   
  3. f = File.open("stones")  
  4.   
  5. while line = f.gets do  
  6.     puts line  
  7. end  
  8.   
  9. f.close  
The readlines reads all lines from the specified file and returns them in the form of an array. 

Directories 
In this section, we work with directories. We have a Dir class to work with directories in Ruby. 
  1. #!/usr/bin/ruby  
  2.   
  3. Dir.mkdir "tmp"  
  4. puts Dir.exists? "tmp"  
  5.   
  6. puts Dir.pwd  
  7. Dir.chdir "tmp"  
  8. puts Dir.pwd  
  9.   
  10. Dir.chdir '..'  
  11. puts Dir.pwd  
  12. Dir.rmdir "tmp"  
  13. puts Dir.exists? "tmp"  
In the second example, we retrieve all of a directory's entries, including its files and subdirectories. 
  1. #!/usr/bin/ruby  
  2.   
  3. fls = Dir.entries '.'  
  4. puts fls.inspect  
The ::entries method returns all entries of a given diretory. We get the array of files and directories of a current directory. The . character stands for the current working directory in this context. The inspect method gives us a more readable representation of the array. 

The third example works with a home directory. Every user in a computer has a unique directory assigned to him. It is called a home directory. It is a place where he can place his files and create his own hierarchy of directories. 
  1. #!/usr/bin/ruby  
  2.   
  3. puts Dir.home  
  4. puts Dir.home 'root'  
Executing external programs 
Ruby has several ways to execute external programs. We will deal with some of them. In our examples we will use well known Linux commands. Readers with Windows or Mac can use commands specific for their systems. 
  1. #!/usr/bin/ruby  
  2.   
  3. data = system 'ls'  
  4. puts data  
We call a ls command which lists directory contents. The system command executes an external program in a subshell. The method belongs to the Kernel Ruby module. 

Below show two other ways of running external programs in Ruby. 
  1. #!/usr/bin/ruby  
  2.   
  3. out = `pwd`  
  4. puts out  
  5.   
  6. out = %x[uptime]  
  7. puts out  
  8.   
  9. out = %x[ls | grep 'readline']  
  10. puts out  
To run external programs we can use backticks `` or %x[] characters. 

We can execute a command with the open method. The method belongs to the Kernel module. It creates an IO object connected to the given stream, file, or subprocess. If we want to connect to a subprocess, we start the path of the open with a pipe character |. 
  1. #!/usr/bin/ruby  
  2.   
  3. f = open("|ls -l |head -3")  
  4. out = f.read  
  5. puts out  
  6. f.close  
  7.   
  8. puts $?.success?  
In the example, we print the outcome of the ls -l | head -3 commands. The combination of these two commands returns the first three lines of the ls -l command. We also check the status of the child subprocess. The $? is a special Ruby variable that is set to the status of the last executed child process. The success? method returns true if the child process ended OK. 

Redirecting standard output 
Ruby has predefined global variables for standard input, standard output and standard error output. The $stdout is the name of the variable for the standard output. In the below example, we redirect a standard output to the output.log file. 
  1. #!/usr/bin/ruby  
  2.   
  3. $stdout = File.open "output.log""a"  
  4.   
  5. puts "Ruby"  
  6. puts "Java"  
  7.   
  8. $stdout.close  
  9. $stdout = STDOUT  
  10.   
  11. puts "Python"  
"Ruby" and "Java" will be written into "output.log"; "Python" will be printed in console.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...