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"