itunes-favourite-albums.rb
# I wonder if my iTunes ratings actually match what I think my favourite albums are?

require 'win32ole'

class Review
  attr_reader :artist, :album, :rating

  def initialize(artist,album,rating)
    @artist = artist
    @album = album
    @rating = rating
  end
  
  def to_s
    "#{@artist} - #{@album}: #{@rating.to_s}"
  end
  
  def <=>(other)
    if (self.rating == other.rating)
      self.artist <=> other.artist
    else
      other.rating <=> self.rating
    end
  end
end

iTunes = WIN32OLE.new('iTunes.Application')
tracks = iTunes.LibraryPlaylist.Tracks

albums = Hash.new

# group the tracks into their respective albums
#   (tracks without an album name will be ignored)
tracks.each{ |track|
  album = track.Album.strip
  if (album != "")
    if (albums[album] == nil)
      albums[album] = Array.new
    end
    albums[album] << track
  end
}

ratings = Array.new

# calculate the average rating for each album
# assumes that an album consists of 6 tracks or more
albums.each_key{ |key|
  rating = 0
  count = 0
  artist = nil
  albumTracks = albums[key]
  albumTracks.each{ |track|
    if (artist == nil)
      artist = track.Artist
    end
    if (track.Rating != 0)
      rating = rating + track.Rating
      count = count + 1
    end
  }
  
  if (count > 5)
    ratings << Review.new(artist, key, ((rating / count) / 20.0))
  end
}

# spit out the albums, highest rated first
puts ratings.sort