Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Notes on working with IO objects
- require 'pp'
- <<-MD
- # IO
- The basis for all input and output in Ruby. It will convert pathnames between different OS conventions, if possible.
- ## Methods of Interest
- * .binread
- * .binwrite
- * .copy_stream
- * .new
- * .open
- * .pipe
- * .read
- * .readlines
- * .write
- * #chars
- * #close
- * #each, #each_byte, #each_char, #each_line
- * #eof
- * #lines
- * #readbyte, #readchar, #readline, #readlines
- * #rewind
- * #to_i
- * #to_io
- * #write
- MD
- <<-MD
- # File
- MD
- # write to file
- filename = "todo.txt"
- # file = File.open(filename, "w") # or
- file = open(filename, "w")
- file.puts "Wash dishes"
- file.puts "Take a walk"
- file.puts "Create hardware startup"
- file.close
- # write to file - block notation
- filename = "groceries.txt"
- File.open(filename, "w") do |file|
- file.puts "hummus"
- file.puts "carrots"
- file.puts "avocados"
- end
- # read from file - block notation
- puts "#{filename} contains:"
- File.open(filename, "r") do |file|
- puts file.read
- end
- # read from file - lines into array
- lines = File.open(filename, "r").readlines
- puts "Reading #{filename} with the #readlines method returns:"
- PP.pp lines
- # checking for existence
- file_check = File.exists?(filename)
- puts "Does #{filename} exist? #{file_check ? 'yes' : 'no'}"
- # getting the path of a the current file
- path = File.dirname(__FILE__)
- puts "The file executing this code is located at #{path}"
- <<-MD
- # Dir
- "Directory streams representing directories in the filesystem."
- ## Methods of Interest
- * Dir[string] - same as Dir.glob(string)
- * .delete
- * .exists?
- * .foreach
- * .home
- * #path
- * #read
- * #rewind
- MD
- # creating a directory
- Dir.mkdir("temp") unless File.exists?("temp")
- # file count
- home = Dir.home
- file_count = Dir.glob("#{home}/*").length
- puts "There are #{file_count} files in the root of your home directory"
- # recursive file count
- file_count = Dir.glob("#{home}/**/*").length
- puts "There are #{file_count} files within your home directory"
- # file count by type
- file_count = Dir.glob("#{home}/**/*.{pdf,PDF}").size
- puts "There are #{file_count} PDFs within your home directory"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement