输入/输出的种类
标准输入/输出
程序在启动后会预先分配3个IO对象。
标准输入
标准输入是用于接收数据的IO对象。可以通过预定义常量STDIN调用IO对象,也可以通过全局变量$stdin引用IO对象。不指定接受者的gets方法等都会默认从$stdin中获取数据。标准输入最初与控制台关联,接收从键盘输入的内容。
标准输出
标准输出是用于输出数据的IO对象。可以通过预定义常量STDOUT调用IO对象,也可以用全局变量$stdout引用IO对象。不知道接受者的puts、print、printf等方法会默认将数据输出到$stdout。标准输出最初与控制台关联
标准错误输出
标准错误输出是用于输出警告、错误的IO对象。可以通过预定义常量STDERR调用IO对象,也可以用全局变量$stderr引用IO对象。用于显示警告信息的warn方法会将信息输出到$stderr。标准版错误输出最初与控制台关联
代码
3.times do |i| $stdout.puts "#{Random.rand}" STDERR.puts "已经输出了#{i+1}次" end
通过一个标准输出,一个错误输出,只有标准输出会被写入文件。
通过tty检查标准输入是否为屏幕的例子
shijianzhongdeMacBook-Pro:chapter_17 shijianzhong$ ruby tty.rb /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/universal-darwin19/rbconfig.rb:229: warning: Insecure world writable dir /usr/local/opt/mysql@5.7/bin in PATH, mode 040777 Stdin is a TTY. shijianzhongdeMacBook-Pro:chapter_17 shijianzhong$ echo | ruby tty.rb /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/universal-darwin19/rbconfig.rb:229: warning: Insecure world writable dir /usr/local/opt/mysql@5.7/bin in PATH, mode 040777 Stdin is not a TTY. shijianzhongdeMacBook-Pro:chapter_17 shijianzhong$ ruby tty.rb < log.txt /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/universal-darwin19/rbconfig.rb:229: warning: Insecure world writable dir /usr/local/opt/mysql@5.7/bin in PATH, mode 040777 Stdin is not a TTY. shijianzhongdeMacBook-Pro:chapter_17 shijianzhong$ cat tty.rb if $stdin.tty? print "Stdin is a TTY. \n" else print "Stdin is not a TTY. \n" end shijianzhongdeMacBook-Pro:chapter_17 shijianzhong$
文件的输入与输出
通过IO类的子类File类可以进行文件的输入/输出操作。
io = File.open(file [, mode[,perm]][, opt])
io = open(file [, mode[,perm]][, opt])
通过上面的方法可以获得一个io对象
mode默认是"r",可以通过设定指定的值,模式跟Python中的open差不多
File操作中,可以通过块变量传递给块。块执行完毕后,块变量引用的File对象也会自动关闭。像Python中的with open as f
File.open("foo.txt") do |file| while line = file.gets ... #执行逻辑 end end
file.closed?检查file对象是否关闭
File.read(file,[, length [, offset]])
不创建File对象,直接读取file里面的数据。length指定读取长度,offset指定从前面第几个字节开始读取数据。如忽略这些参数,程序会从头到位一次性读取文件内容
File.binread(file,[, length [, offset]])
二进制的方式读取文件
FIle.write(file[,data[,offset]])
不创建File对象,直接向file写入data。省略参数offset时,会将文件的全部内容替换为data,指定该参数时,则会将前面offset个字节写入文件,后面的数据则保持不变
>> text = "Hello,Ruby!\n" => "Hello,Ruby!\n" >> File.write("hello.txt", text) => 12 >> p File.read("hello.txt") "Hello,Ruby!\n" => "Hello,Ruby!\n" >> File.write("hello.txt", "12345", 5) => 5 >> p File.read("hello.txt") "Hello12345!\n" => "Hello12345!\n" >>
File.binwrite(file[,data[,offset]])
以二进制模式打开并写入file
基本的输入/输出操作
对于io对象的基本操作。
输入操作 io.gets,io.each,io.each_line,io.readlines
原文:https://www.cnblogs.com/sidianok/p/13069885.html