11.讀寫
標準輸入流:gets 讀檔案
file.open("hello.rb","r") do |file|
while line = file.gets
puts line #列印出檔案內容
endend
標準輸出流:puts
兩者的區別是puts會在引數後面新增回車換行,print不會新增
printf("number:%5.2f,\nstring:%s\n",1.23,"hello") 這個語法跟c相同就不多說了
%5.2f 匹配 1.23
%s 匹配字串
[plain]view plain
copy
1.先寫段**看看
#p1
myfile = file.new("f:\\ruby\\mycode\\hello.rb","w");
myfile.puts "puts 'aa'"
myfile.puts "puts 'bb'"
myfile.close #只有close掉了內容才被寫入檔案裡面。
windows中路徑 "\\"
檔案hello.rb寫入上面兩行**
建立檔案:file.new("hello.rb","w")
刪除檔案:file.delete("")
讀取檔案:file.open("hello.rb","r") do |file|
while line = file.gets #標準輸入流
puts line
end
end
#讀檔案
print "please input a file name:"
filename = gets
if filename &&!filename.empty?#檔案存在
filename = filename[0,filename.length-1]
#去掉檔名後面的"\n"
else
print "the file name can't be null!"
exit(1)
end
if file.exist?(filename)
puts "*****====#*****===="
file.open(filename,"r") do |file|
while line = file.gets
puts line
end
end
puts "***************==="
else
puts "the program can't find the file #"
end
print "press any key to contiue..."
gets
#寫檔案
puts "***********************************==="
puts "this program is about ruby write file."
puts "***********************************==="
print "please input file name: "
filename=gets
if filename&&!filename.empty?
filename=filename[0, filename.length-1]
else
puts "the file name can't been null!!"
exit 1;
end
file=nil
unless file.exist?(filename)#條件不成立的時候執行
puts "the system cannot find the file specified!"
print "[c] to create a new file and [e] to exit the program: "
option=gets
if option&&!option.empty?
option=option.chomp#去掉"\n"
else
puts "bye!"
exit 1;
end
case option.downcase
when "c" : file=file.new(filename, "w")
when "e" : exit 0
else
puts "invalid arguments!! the program has stop. "
exit 0
end
else
file=file.new(filename, "w")
end
print "now please input content: "
content=gets
file.print content
file.close
print "press any key to continue...."
gets
ruby 讀寫檔案
ruby 讀寫檔案 ruby 讀取檔案 方法一 file file.open users desktop demo.txt r while line file.gets puts line end 方法二 file.open users desktop demo.txt r each line do...
ruby 讀取yaml檔案
假如我們有乙個寫好的yaml檔案 program id 1 input 1 2 output 3 注意 後面必須有乙個空格 讀取方式 require yaml problem yaml.load file.open a.yaml puts problem id is puts problem inp...
ruby 生成檔案
1.建立檔案 建立乙個檔案,引數1 檔名,引數2 對檔案的操作,w 讀寫 w 只寫 r 讀寫 r 只寫 f file.new test1.txt w 寫入檔案內容 f.puts test 最後關閉檔案,釋放這個執行緒.f.close 2.指定檔案的路徑 建立路徑path,引數1 檔案的路徑,引數2 ...