【发布时间】:2013-09-04 14:03:45
【问题描述】:
我目前有一个涉及很多新类实例的系统,所以我不得不使用数组来分配它们,如下所示:Create and initialize instances of a class with sequential names
但是,每当出现新实例时,我都必须不断添加新实例,而不会覆盖现有实例。对我现有代码进行一些验证和修改版本可能是最佳选择吗?
这是我的代码,目前每次运行都会覆盖现有数据。我希望状态发生变化时被覆盖,但我也希望能够在其中永久存储一两个变量。
E2A:忽略全局变量,它们只是用于测试。
$allids = []
$position = 0 ## Set position for each iteration
$ids.each do |x| ## For each ID, do
$allids = ($ids.length).times.collect { MyClass.new(x)} ## For each ID, make a new class instance, as part of an array
$browser.goto("http://www.foo.com/#{x}") ## Visit next details page
thestatus = Nokogiri::HTML.parse($browser.html).at_xpath("html/body/div[2]/div[3]/div[2]/div[3]/b/text()").to_s ## Grab the ID's status
theamount = Nokogiri::HTML.parse($browser.html).at_xpath("html/body/div[2]/div[3]/div[2]/p[1]/b[2]/text()").to_s ## Grab a number attached to the ID
$allids[$position].getdetails(thestatus, theamount) ## Passes the status to getdetails
$position += 1 ## increment position for next iteration
end
E2A2:从我的评论中粘贴这个:
嗯,我只是在想,我首先将以前的值转储到另一个变量中,然后另一个变量获取新值,并遍历它们以查看是否有任何与以前的值匹配。这是一种相当混乱的方法,我在想,self.create 会用 ||= 工作吗? – 乔 7 分钟前
【问题讨论】:
-
您能准确地说出您想永久存储哪些数据和哪个变量吗?
-
当然,非常感谢您的回复 :) 应该保留(至少保留一点)的数据将是 thestatus ,并且将永久存储在那里的外部变量将被调用进度和消息计数。
-
嗯,我只是在想,我首先将以前的值转储到另一个变量中,然后另一个变量获取新值,并遍历它们以查看是否有任何匹配以前的值。这是一种相当混乱的方式,但我在想,self.create 会用 ||= 工作吗?