title: refactoring Ruby scraping code
body: <p>Basically, I will have multiple <code>.main_entry</code> blocks on each page and I will need to pull a couple of pieces of data from each. How can this be properly refactored into methods? </p>
  
  <pre><code>require 'open-uri'
  require 'nokogiri'
  
  
  url = #url
  doc = Nokogiri::HTML(open(url))
  
  doc.css(".main_entry").each do |item|
    artist = item.at_css(".list_artist").text
    title = item.at_css(".list_album").text
    puts "#{artist} - #{title}"
  end
  </code></pre>
  
  <p>I have arrived at this mess below, which throws the <code>undefined local variable or method 'release'</code> error that seems to be related to methods being over-written. Could you explain to me what process the code below goes through, why it breaks down and what I should turn to for the fix? Should each <code>.main_entry</code> block be saved into some kind of a cache or an array first, before instantiating? </p>
  
  <pre><code>require 'open-uri'
  require 'nokogiri'
  
  class Scraper
    def initialize(url)
      @url = url
    end
  
    def release
      @release ||= doc.css(".main_entry") || []
    end
  
    release.each do |item|
      define_method(:artist) do
        @artist ||= item.at_css(".list_artist").text
      end
  
      define_method(:title) do
        @title ||= item.at_css(".list_album").text
      end
    end
  
    private
    attr_reader :url
  
    def doc
      @doc ||= Nokogiri::HTML(open(url))
    end
  end
  
  scraper = Scraper.new( #url
  
  puts "#{scraper.artist} - #{scraper.title}"
  </code></pre>