在数组内创建新的类实例而不覆盖现有的实例

时间:2013-09-01 08:37:50

标签: ruby arrays class map

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

嗯,我只是想,我开始将先前的值转储到另一个变量,然后另一个变量抓取新值,并迭代它们以查看是否与先前的值匹配。尽管如此,这是一个非常混乱的方式,我在想,会自我创造一个|| =工作吗? - 乔7分钟前

1 个答案:

答案 0 :(得分: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创建一个类的实例,但始终更新其状态和数量。