ruby輸入與輸出

Paste_Image.png
Paste_Image.png

下面ruby程序?qū)崿F(xiàn)cat命令,把一個(gè)文本文件復(fù)制為一個(gè)新的文件
vim cat.rb
IO.copy_stream(STDIN,STDOUT)
然后執(zhí)行:(前提是要有aaa.txt文件存在)
ruby cat.rb < aaa.txt > output.txt
我們查看是否復(fù)制了一個(gè)文件

Paste_Image.png

字符串寫入文件案例:


Paste_Image.png

vim write.rb

File.dirname(FILE),表示當(dāng)前文件的家目錄,write.txt表示要寫入內(nèi)容的文件

abs_path = File.expand_path("write.txt",File.dirname(FILE))

絕對(duì)路徑,下面2行是寫入的文件內(nèi)容

IO.write abs_path, <<EOF
Line 1, first line
Line 2, second line
EOF

執(zhí)行
ruby write.rb
[root@master1 ruby]# cat write.txt
Line 1, first line
Line 2, second line
[root@master1 ruby]#

字符串讀入文件案例


Paste_Image.png

vim read.rb

讀取一個(gè)存在的文件

file_path = File.expand_path("write.txt",File.dirname(FILE))
puts(IO.read file_path)

讀取一個(gè)不存在的文件

unexist_path = File.expand_path("unexist.txt",File.dirname(FILE))
begin
puts(IO.read unexist_path)
rescue SystemCallError => e
puts(e.class)
puts(e)
end

[root@master1 ruby]# ruby read.rb
Line 1, first line
Line 2, second line
Errno::ENOENT
No such file or directory - /m8/ruby/unexist.txt
[root@master1 ruby]#

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容