From: Luke Cowell Date: 2009-04-25T09:40:31+09:00 Subject: Re: Finding Quiz Responses (#200) It's late, but it's here.. my very first ruby quiz submission: #!/usr/bin/env ruby require 'rubygems' require 'hpricot' require 'open-uri' require 'cgi' def build_quiz_uri(quiz_num) query = CGI::escape("subject:(+#{quiz_num}) +quiz") base_url = "http://www.ruby-forum.com/search?query=" uri_string = (base_url + query) URI.parse(uri_string) end def get_quiz_response_url(uri_string) doc = Hpricot(open(uri_string)) quiz_table = doc.at("table[@class='topics list]") quizzes = quiz_table.search("tr[@class$='new-posts ']") highest_replies = 0 link = "" #find the quiz that has the right subject and has the most replies quizzes.each do |quiz| subject = quiz.at("td[@class='subject']/a").innerHTML quiz_subject = "#" + Quiz_num.to_s if(subject.include?(quiz_subject)) replies = quiz.at("td[@class='replies']").innerHTML.to_i if(replies > highest_replies) highest_replies = replies link = quiz.at("td[@class='subject']/a")[:href] end end end #trim the excess anchor link.gsub(/#.*$/, "") end def get_responses(url) doc = Hpricot(open(url)) response_elements = doc.search(".post") responses = [] response_elements.inject([]) do |responses, response| link = url + response.search("div[@class='subject]").at("a")[:href] author = response.search("span[@class]='name'").text.split("(").first.strip responses << {:link => link, :author => author} end #remove the first quiz (which is from the quizmaster) responses.delete_at(0) #if the summary has been posted, we want to remove that too #it's difficult to know if we should actually remove the response... if(responses.length > 0) if(QuizMaster_Name.include?(responses.last[:author])) responses.pop end end responses end Quiz_num = 100 QuizMaster_Name = ["Di Mo", "James Gray"] query_uri = build_quiz_uri(Quiz_num) response_path = get_quiz_response_url(query_uri) response_url = query_uri.scheme + "://" + query_uri.host + response_path puts get_responses(response_url).to_yaml -- Posted via http://www.ruby-forum.com/.