2017-05-30 37 views
0

我通過我的bin文件夾在本地運行我的程序;這只是一個小型的CLI項目。我正試圖剝離並將字符串推入數組中。剝離並將字符串推入數組

這裏是我的代碼:

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 

當我運行我的程序,我得到一個錯誤:

block in scrape_places': undefined method `<<' for nil:NilClass (NoMethodError) 

任何建議都非常讚賞。

回答

2

簡而言之:你有undefined method '<<' for nil:NilClass,因爲你是試圖操縱類實例變量@places,它的價值是nil

第一個@places在方法initialize是對象實例變量,則其值設置爲[],但是在類方法self.scrape_places第二個@places是一個類的實例變量,我以前不給它的任何值,所以它默認爲零。注意兩個變量不一樣。既然你認爲它們是一樣的,所以你可能想把def self.scrape_places改爲def scrape_places,那麼它們將是同一個對象實例變量。

還看到:

Ruby class instance variable vs. class variable

+0

感謝您的反饋和文章! – schall