Skip to content

Instantly share code, notes, and snippets.

@leimd
Created June 29, 2015 19:16
Show Gist options
  • Save leimd/a1f9bda29c72968b17b4 to your computer and use it in GitHub Desktop.
Save leimd/a1f9bda29c72968b17b4 to your computer and use it in GitHub Desktop.
File class
#Dir Class exercise
#Dir.glob returns an array of filenames
#
puts Dir.glob("../01IO/*").length
puts Dir.glob("../01IO/*.rb").join("\n")
#
#Create 500 files with extension of a,b,c,d,e#
fdir = "../01IO/Files/"
(1..500).each do |i|
ffull = fdir + i.to_s + '.a' + rand(1..5).to_s
f = File.open(ffull,'w') {|f| f.puts "sssssssssssssssssssssssssssssssssssssssdddddddddddddd"} # puts random stuff into each file so that the size of files are not zero
end
puts "500 Files creation done!"
#-----------------File Histogram problem-------------
glob = Dir.glob(fdir + "**/*.*") #Returned an array of all file names
histo = Hash.new() # First index is file number sum and second index is file size sum, hash key is file type
glob.each do |fname|
ext = fname.split(".")[-1].to_s.downcase
histo[ext] ||= [0,0]
histo[ext][0] += 1
histo[ext][1] += File.size(fname)
end
puts histo #Print the histo Hash table
require 'open-uri'
rname = "Hello"
somefile = File.open(rname,'w') {|f| 3.times {f.puts "Hello2"}}
#wikipedia Example
#
remote_base_url = "https://en.wikipedia.org/wiki"
remote_page_name = "Montreal"
remote_full_url = remote_base_url + "/" + remote_page_name
remote_data = open(remote_full_url).read
my_local_file = File.open("Wiki",'w')
my_local_file.write(remote_data)
my_local_file.close
#------------------------------#
# read file exercise
#
thefile = File.open(rname,'r')
puts thefile.readlines #This can be thefile.read, thefile.readline, thefile.readlines
## Use readline because file sometimes can get big, and by using readline, it only loads one line at a time.
#----EOF------##
puts "End of File" if thefile.eof?
#--------------Exercise: Readlines-----------------
url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
local_fname = "hamlet.txt"
File.open(local_fname,'w') {|file| file.write(open(url).read)}
File.open(local_fname,'r') do |file|
file.readlines.each_with_index do |line,idx|
puts line if idx % 42 == 0
end
end
#------------ Only Hamlet's lines --------------------
puts "\n" * 5 # print five blank lines
File.open(local_fname,'w') {|file| file.write(open(url).read)}
File.open(local_fname,'r') do |file|
file.readlines.each_with_index do |line,idx|
puts line if line.match("Ham\.")
end
end
#---------Check for file existance -----------#
puts "\n" * 10
puts "Returns if tom file exists"
fname = "tom"
puts File.exists?(fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment