Skip to content

Instantly share code, notes, and snippets.

@Noffica
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noffica/96de8f80ecc67714c56d to your computer and use it in GitHub Desktop.
Save Noffica/96de8f80ecc67714c56d to your computer and use it in GitHub Desktop.
File I/O
fname = "sample.txt"
somefile = File.open(fname, "w")
somefile.puts "Hello file!"
somefile.close
require 'rubygems'
require 'rest-client'
require 'open-uri'
hamlet_url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
# Create the Hamlet file
File.open("hamlet.txt", "w") do |file|
file.write(RestClient.get(hamlet_url))
end
# Print every 42nd line
File.open("hamlet.txt", "r").readlines.each_with_index do |line, index|
if ((index + 1) % 42 == 0)
puts line
end
end
# Solution (alternate)
# 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
# Print only Hamlet's lines
file = File.open("hamlet.txt", "r")
while !(file.eof?)
puts file.readline.scan(/^\s\s(Ham).+/)
end
require 'rubygems'
require 'rest-client'
require 'open-uri'
# Write to a file
File.open("wiki-page.html", "w") do |file|
file.write "http://en.wikipedia.org/"
end
# Get / Fetch a file (from the web)
File.open("wiki-page-actual.html", "w") do |file|
file.write(RestClient.get("http://en.wikipedia.org"))
end
# Read a file
contents = File.open("wiki-page.html", "r") { |file| file.read }
puts contents
print "\n"
# Readlines
File.open("sample.txt").readlines.each { |line|
puts line
}
print "\n"
# Readline
file = File.open("sample.txt", "r")
while !(file.eof?)
line = file.readline
puts line
end
print "\n"
# Get / Fetch a file (from the web) then read it.
url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
puts open(url).readline
print "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment