sivanes
sivanes

Reputation: 733

creating methods within an interation in Ruby?

The code below obviously does not work, but this is what I had in mind. Is there a way to create methods like the two below using item, without repeating the doc.css(".main_entry").each do |item| over and over?

class Scraper      
.
.
.
  doc.css(".main_entry").each do |item|
    def artist 
      @artist ||= item.at_css(".list_artist").text
    end

    def title
      @title ||= item.at_css(".list_album").text
    end
  end
.
.
.
end

puts scraper.artist
puts scraper.title

Upvotes: 0

Views: 38

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

You almost have it. However, method scopes don't nest, the only construct in Ruby that creates a nested scope is a block. Thankfully, there is a method for defining methods that takes a block as an argument:

class Scraper      
.
.
.
  doc.css(".main_entry").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
.
.
.
end

puts scraper.artist
puts scraper.title

However, note that this has the exact same problem that your original code would have had if it had worked: you are simply overwriting the same method over and over and over again.

Upvotes: 2

Related Questions