【问题标题】:Creating new class instances inside an array without overwriting existing ones在数组中创建新的类实例而不覆盖现有实例
【发布时间】: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 会用 ||= 工作吗?

标签: ruby arrays class map


【解决方案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创建一次你的类的实例,但总是更新它的状态和数量。

【讨论】:

  • 你知道,我真的很喜欢人们解释代码为什么起作用,而不仅仅是代码起作用的原因。非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 2020-05-11
  • 2011-11-12
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多