Common Ruby file operation code instances and ruby code instances

Source: Internet
Author: User

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 ")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.