FILE IN RUBY
use file open
-> hava a file class
filename= "test9.cpp"
File.open(filename) do |files|
while line= files.gets
puts line
end
end
files.gets => จะ return แต่ละบรรทัด มาให้
File.writable? filename
File.readable? filename
File.executable? filename
File.exist? filename
do not close file any where
def test2
yield 1
yield 2
end
test2 {|x| if x>0 then puts x else puts "error" end }
หรือ
test2 {|x| if x>0 ; puts x else puts "error" end }
test2 {|x| if x>0 : puts x else puts "error" end }
...
Easy way to read file
filename ="helloworld"
IO.foreach(filename){|line|puts line}
str=IO.read(filename) //read file into the string
puts str
arr=IO.readlines(filename) // read line of file into the Array
How to write a file
File.open(" ......... ","w") do |filecontent|
filecontent.puts "hello world"
end
Binary file vs Text file
Text File โดยทั่ว ๆ ไปโปรแกรมจะต้องมองเรื่องของการ encode/decode ไฟล์ในการ อ่านและเขียน การ encode/decode นี้ก็เช่นวิธีการเก็บไฟล์เป็น ภาษาไทย ภาษาจีน หรือ ภาษาอังกฤษ นั่นเอง ซึ่งแต่ละภาษาจะมีวิธีการเก็บที่แตกต่างกันเช่น ASCII, ISO, Unicode, JIF และอื่น ๆ
Binary File โดยทั่ว ๆ ไปจะหมายถึงการที่โปรแกรมมองเรื่องของการอ่านและเขียนไฟล์ในรูปแบบของ byte-to-byte หรือก็คืออ่านเป็น byte และเขียนเป็น byte โดยไม่สนใจการ encode/decode ต่าง ๆ เลยครับ
ruby ให้เราอ่าน textfile และแก้ไข text file ได้ ส่วน binary file สามารถอ่านได้แต่ จะต้องหาlibrary มาลงจึงจะสามารถ จัดการ กับ binary file ได้
Work with Directory
//use Dir class
Dir.mkdir(path) =>create directory in that path
Dir.pwd
Dir.entries(Dir.pwd)
Dir.entries('.')
FileUtils
-------------------------
require 'fileutils' //you can use file utility to use a Unix - Dos command
such as=> Fileutils.pwd()
Read and Write file(.csv) -> format for holding data
require 'csv'
CSV.open(filename,'w') do|data|
data <<['...','.....','......']
end
CSV.open(filename,'r') do |data|
p data
end
p is a shotcut of "puts"
Regular Expression is a string to match a particular thing that
you're searching for
such as str.gsub(/[a-z]/,"*") output=>
ไม่มีความคิดเห็น:
แสดงความคิดเห็น