Common Ruby file operation code instances and ruby code instances
# Create a 222. rb file and the input character File = file. open ("222.rb"," w + ") file. puts "123 \ nwadwa \ n12124124 \ ndwdw" file. close # output 222. rb content File. open ("222.rb"," r + ") do | file | while line = file. getsputs lineendend # directly use IO to operate the file IO. foreach ("222.rb") do | line | puts line if line = ~ /Abc/# The output matches the 'abc' row puts line if line !~ /Qwe/# The output does not match the end of the row where 'Qi' is located # the absolute path of the output File puts File. expand_path ("222.rb") # count chars from a filefile = File. new ("222.rb") w_count = 0file. each_byte do | byte | w_count + = 1 if byte =? 1 endputs "# {w_count}" # create new file and write some words thereprint "The file now is exist? --> "Puts File. exist? ("Asd.txt") # determine whether a file exists. File = file. new ("asd.txt", "w") print "The file now is exist? --> "Puts File. exist? ("Asd.txt") file. write ("hehe \ nhahah") # io. stream operationrequire 'stringio 'ios = stringio. new ("abcdef \ n ABC \ n 12345") ios. seek (5) # Move the offset pointer to 5 (where e letters are located) ios. puts ("xyz3") # overwrite the original data puts ios from 5. tell # tell -- Returns the current offset (in bytes) of ios. puts ios. stringputs ios. string. dump # ignore the escape of \ n # another examplerequire 'stringio 'ios = stringio. new ("abcdef \ nq9ert \ n 12345") ios. seek (3) ios. ungetc (? W) # replace the char at index 3 puts "Ptr = # {ios. tell} "s1 = ios. gets # filte the "\ n" s2 = ios. getsputs s1puts s2 # open the File in Ruby and write data. txt = File. open ("file path", "w +") txt. puts 'content of the file to be written 'txt. close # read data from the File num = File. readlines ("file path") [0]. chomp # method for opening a file system ("notepad file path ")