>Technical – "Programing in Ruby"

>This is another book from The Pragmatic Programmer publishers. This is a pretty thick book, which includes an introduction to Ruby as well as a long library reference. I’ve read some of the introductory chapters, but I use it mostly for reference while hacking some Ruby code.

One early program I wrote was to help my friend Jack download a bunch of MP3 files that were refernced by a specific web page. Here is the code:

require "net/http"require "open-uri"

def get_page (uri) 
 # split into parts 
  uri =~ %r{http://((\w|\.)*)} 
  @@domain = $1 
  file = $'# connect to the web server and fetch the page ' puts "-->> Connecting to domain #{@@domain}\n" #" result = "" Net::HTTP.start(@@domain,80) {|http|   response = http.get(file)   result = response.body } resultrescue puts "Unable to open #{uri}"end

def download_mp3 (base_uri, file) u = base_uri + file # Replace blanks by _ in file name fname = file.gsub("%20", "_") if (File.exists?(fname))   puts "--> Already have #{fname}" else   puts "--> Saving "   f = File.open(fname, "w");   u = OpenURI.open_uri(u)   f.write(u.read)  endrescue puts "Unable to save #{fname}"end

if (ARGV.length == 0) puts "Usage: get_mp3.rb "else base_uri = ARGV[0] page = get_page(ARGV[0]) count = 0 page.scan(%r{<a href=((.)(.)*\.mp3)}) {   download_mp3(base_uri, $1[1..-1])   count += 1 } puts ">>> Downloaded #{count} files...\n"end

This program probably could be made shorter, but it does work. I had fun trying to come up with proper regular expression.

This book is “the” Ruby reference at this point and I have so far only scratched the surface. Meanwhile I’m working on another project with Ruby and Ruby on Rails – a program to index MP3 files.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s