Skip to content

Instantly share code, notes, and snippets.

@Leejojo
Created June 27, 2016 17:08
Show Gist options
  • Save Leejojo/a85519a4894e440290b02b0c367834ab to your computer and use it in GitHub Desktop.
Save Leejojo/a85519a4894e440290b02b0c367834ab to your computer and use it in GitHub Desktop.
I/O Excerises
require 'rubygems'
require 'rest-client'
fname = "sample.txt"
somefile = File.open(fname, "w")
somefile.puts "Hello file!"
somefile.close
wiki_url = "http://en.wikipedia.org/"
wiki_local_filename = "wiki-page.html"
File.open(wiki_local_filename, "w") {|file| file.write (RestClient.get(wiki_url))}
file = File.open("sample.txt", "r")
contents = file.read
puts contents
File.open("sample.txt").readlines.each do |line|
puts line
end
file = File.open("sample.txt", 'r')
while !file.eof?
line = file.readline
puts line
end
require 'open-uri'
url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
puts open(url).readline
require 'open-uri'
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 == 41
end
end
datafile = File.open("sample.txt", "r")
lines = datafile.readlines
datafile.close
lines.each{ |line| puts line }
lines = File.open("sample.txt", "r"){ |datafile|
datafile.readlines
}
lines.each{|line| puts line}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment