Reputation: 29
I am running my program locally through my bin folder; this is just a small CLI project. I am trying to strip and push strings into an array.
Here is my code:
require 'nokogiri'
require 'open-uri'
module BestPlaces
class Places
attr_accessor :name, :population, :places
def initialize
@places = []
end
def self.scrape_places
doc = Nokogiri::HTML(open("https://nomadlist.com/best-cities-to-live"))
places = doc.search("div.text h2.itemName")
ranks = doc.search("div.rank")
places.each{|e| @places << e.text.strip}
@places.each do |place|
i = @places.index(place)
puts "#{ranks[i].text}. #{place}"
end
end
end
class CLI
def list_places
puts "Welcome to the best places on Earth!"
BestPlaces::Places.scrape_places
end
def call
list_places
menu
goodbye
end
end
end
When I run my program, I get an error:
block in scrape_places': undefined method `<<' for nil:NilClass (NoMethodError)
Any suggestions are much appreciated.
Upvotes: 0
Views: 55
Reputation: 6125
In short: you got undefined method '<<' for nil:NilClass
, because you are try manipulate an class instance variable @places
and it's value is nil
.
The first one @places
in method initialize
is an object instance variable, you set its value to []
, but the second one @places
in class method self.scrape_places
is a class instance variable, you did't give any value to it, so it's nil by default. Notice the two variable are not the same. Since you supposed they are the same, so you may want change def self.scrape_places
to def scrape_places
, then they will be the same object instance variable.
see also:
Ruby class instance variable vs. class variable
Upvotes: 2