Advertisement
Guest User

Untitled

a guest
May 31st, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. # Notes on working with IO objects
  2.  
  3. require 'pp'
  4.  
  5. <<-MD
  6. # IO
  7.  
  8. The basis for all input and output in Ruby. It will convert pathnames between different OS conventions, if possible.
  9.  
  10. ## Methods of Interest
  11.  
  12. * .binread
  13. * .binwrite
  14. * .copy_stream
  15. * .new
  16. * .open
  17. * .pipe
  18. * .read
  19. * .readlines
  20. * .write
  21. * #chars
  22. * #close
  23. * #each, #each_byte, #each_char, #each_line
  24. * #eof
  25. * #lines
  26. * #readbyte, #readchar, #readline, #readlines
  27. * #rewind
  28. * #to_i
  29. * #to_io
  30. * #write
  31. MD
  32.  
  33. <<-MD
  34. # File
  35. MD
  36.  
  37. # write to file
  38. filename = "todo.txt"
  39. # file = File.open(filename, "w") # or
  40. file = open(filename, "w")
  41. file.puts "Wash dishes"
  42. file.puts "Take a walk"
  43. file.puts "Create hardware startup"
  44. file.close
  45.  
  46. # write to file - block notation
  47. filename = "groceries.txt"
  48. File.open(filename, "w") do |file|
  49. file.puts "hummus"
  50. file.puts "carrots"
  51. file.puts "avocados"
  52. end
  53.  
  54. # read from file - block notation
  55. puts "#{filename} contains:"
  56. File.open(filename, "r") do |file|
  57. puts file.read
  58. end
  59.  
  60. # read from file - lines into array
  61. lines = File.open(filename, "r").readlines
  62. puts "Reading #{filename} with the #readlines method returns:"
  63. PP.pp lines
  64.  
  65. # checking for existence
  66. file_check = File.exists?(filename)
  67. puts "Does #{filename} exist? #{file_check ? 'yes' : 'no'}"
  68.  
  69. # getting the path of a the current file
  70. path = File.dirname(__FILE__)
  71. puts "The file executing this code is located at #{path}"
  72.  
  73.  
  74. <<-MD
  75. # Dir
  76.  
  77. "Directory streams representing directories in the filesystem."
  78.  
  79. ## Methods of Interest
  80.  
  81. * Dir[string] - same as Dir.glob(string)
  82. * .delete
  83. * .exists?
  84. * .foreach
  85. * .home
  86. * #path
  87. * #read
  88. * #rewind
  89. MD
  90.  
  91. # creating a directory
  92. Dir.mkdir("temp") unless File.exists?("temp")
  93.  
  94. # file count
  95. home = Dir.home
  96. file_count = Dir.glob("#{home}/*").length
  97. puts "There are #{file_count} files in the root of your home directory"
  98.  
  99. # recursive file count
  100. file_count = Dir.glob("#{home}/**/*").length
  101. puts "There are #{file_count} files within your home directory"
  102.  
  103. # file count by type
  104. file_count = Dir.glob("#{home}/**/*.{pdf,PDF}").size
  105. puts "There are #{file_count} PDFs within your home directory"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement