【问题标题】:warning: already initialized警告:已经初始化
【发布时间】:2014-11-16 01:55:51
【问题描述】:

我是 ruby​​ 编码的新手,我想知道为什么在运行下面的代码时会收到警告。

我检查了一些类似问题的答案,但似乎无法让它对我有用。

您知道为什么会发生这种情况以及如何解决吗?

非常感谢!

这是我在终端中收到的警告

test_Amazon.rb:9: warning: already initialized constant PAGE_URL
test_Amazon.rb:9: warning: previous definition of PAGE_URL was here

代码如下:

require 'rubygems'
require 'nokogiri'   
require 'open-uri'



for $i in (1..5)

PAGE_URL = "http://www.amazon.com/Best-Sellers/zgbs/automotive/?pg=#$i"
page = Nokogiri::HTML(open(PAGE_URL))

    page.css(".zg_itemWrapper").each do |item|  
        price = item.at_css(".zg_price .price").text
        asin =  item.at_css(".zg_title a")[:href].split("/")[5].chomp
        product_name = item.at_css(".zg_title a")[:href].split("/")[3]

        puts "#{asin} #{price} #{product_name}"

    end
end  

【问题讨论】:

    标签: ruby warnings constants


    【解决方案1】:

    大写变量实际上是常量。当您更改常量的值时,您会收到此警告。为避免在您的示例中出现此警告,请使用局部变量而不是常量来存储 URL:

    5.times do |i|
      page_url = "http://www.amazon.com/Best-Sellers/zgbs/automotive/?pg=#{i+1}"
      page = Nokogiri::HTML(open(page_url))
    
      page.css(".zg_itemWrapper").each do |item|  
        ...
      end
    end
    

    您应该避免的另一件事是像$i 这样的全局变量。几乎没有理由在整个代码库中拥有可全局访问的变量。

    【讨论】:

    • 非常感谢斯派克曼!我可以通过将 page_url 设为小写来摆脱警告。使用“.times”与“for in”有什么好处吗?
    • 是的,有一个好处。 for ... in 污染了另一个命名空间。而times 中的块变量(如eachmap)在块结束后不再设置。因此for ... in 没有在Ruby 中使用。您可能想阅读The Evils of the For Loop
    猜你喜欢
    • 2011-01-02
    • 2011-08-29
    • 2011-11-29
    • 2012-10-08
    • 2011-08-20
    • 2019-05-23
    • 1970-01-01
    • 2014-03-02
    • 2013-09-24
    相关资源
    最近更新 更多