2013-09-01 21 views
0

我目前已经有一个涉及到很多新类实例的系统,所以我必须使用一个数组来分配它们,如下所示: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:要去粘贴从我的评论:

嗯,我只是在想,我开始通过将以前的值转储到另一个变量,那么另一个变量抓住新的价值观,和迭代通过它们查看是否有与之前的值相匹配的值。虽然这是一个相当混乱的方式,但我想,会自动创建一个|| = work? - Joe 7分钟前

+1

您能准确地说出哪些数据以及您想永久存储哪个变量吗? – hedgesky

+0

当然,非常感谢回应:)应该保留的数据(至少一点点)将是状态,并且永久存储在那里的外部变量将被称为进度和消息计数。 – Joe

+0

嗯,我只是在想,我开始时将先前的值转储到另一个变量中,然后另一个变量抓取新的值,并遍历它们以查看是否有与之前的值相匹配的值。虽然这是一个相当混乱的方式,但我想,会自动创建一个|| = work? – Joe

回答

1

如果我理解正确,您需要存储每个ID的状态和金额,对不对?如果是的话,那么这样的事情会帮助你:

# I'll store nested hash with class instance, status and amount for each id in processed_ids var 
$processed_ids = {} 

$ids.each do |id| 
    processed_ids[id] ||= {} # 
    processed_ids[id][:instance] ||= MyClass.new(id) 
    processed_ids[id][:status] = get_status # Nokogiri method 
    processed_ids[id][:amount] = get_amount # Nokogiri method 
end 

这是什么代码做的事:它只有一次创建类的每个ID的情况下,却总是更新其状态和数量。

+0

你知道,当人们解释为什么代码能够工作时,我真的很喜欢它,而不是代码的工作原理。非常感谢! :) – Joe

相关问题