2012-12-01 96 views
0

运行我下面的Ruby脚本时,我收到以下错误:红宝石,没有方法错误

s3parse.rb:12:in `block in <class:AccountLog>': undefined method `extract_account_id' for AccountLog:Class (NoMethodError) 

我不认为它应该是一个类的方法,是有一个原因它不是以我的方法考虑?

class AccountLog 
attr_accessor :bytes, :account_id, :date 

    def extract_account_id(line) 
      line.match(%r{accounts/(\d+)}).captures.join.to_i 
    end 

    s3log = File.open('vidcoder.txt').each do |line| 
     account_log = AccountLog.new 
     account_log.date = line.match(%r{\[[^:]*}).to_s.delete"[" #need to finish this regex to make it work 
     account_log.account_id = extract_account_id(line) 
     account_log.bytes = line.match(%r{^.*\s+HTTP.*\s+-\s+(\d+)\s+}).captures.join.to_i 
     puts "\n" 
     puts "The api request on #{account_log.date} was fromm account number #{account_log.account_id} and the bytes were #{account_log.bytes}" 
    end 

end 
+0

你可以发布s3parse.rb或至少使用AccountLog类的相关部分吗? – jboursiquot

+0

嗨,这是整个类和文件,我只是从命令行运行该文件,我的目标是将正则表达式重构为单独的方法,以使其更好地读取 – BC00

+0

您正在尝试使用s3log变量?如果这是一个ruby脚本,你应该将该逻辑移出课程之外。 –

回答

3

def extract_account_id将定义一个实例方法。

在你调用它的方式中,你需要一个类方法。

将其定义是这样的:

def self.extract_account_id(line) 

,或者因为你已经有一个AccountLog实例,用它来打电话extract_account_id

account_log.account_id = account_log.extract_account_id(line) 

请注意,使用第二种方法,你不需要修改方法定义,只需通过account_log实例调用extract_account_id即可。

我想你会想s3log = File...以外的类定义。

或者使用一个常量:S3log = ...

然后你就可以访问它AccountLog::S3log

+0

谢谢大家。我将其更改为account_log.extract_account_id(行),它正常工作。由于帐户ID的提取应该在实例(个人s3log)上,我认为使用实例方法而不是类方法是有意义的。 – BC00

+0

@ BC00我可能是错的,但是您从文件行中提取ID以将其存储在实例中。这听起来更像是类方法的工作而不是实例方法。即使你没有一个AccountLog的实例,你仍然应该能够从一行文本中提取ID号? –

0

有没有你不认为它应该是一个类的方法的原因吗?你在一个类方法的上下文中使用它,这就是为什么它说没有类AccountLog的这种方法。

如果您将您的方法命名为self.extract_account_id(line),我相信它会起作用。

从你正在尝试做什么我认为这是你在找什么?

class AccountLog 
    attr_accessor :bytes, :account_id, :date 

    def self.extract_account_id(line) 
    line.match(%r{accounts/(\d+)}).captures.join.to_i 
    end 
end 

s3log = File.open('vidcoder.txt').each do |line| 
    account_log = AccountLog.new 
    account_log.date = line.match(%r{\[[^:]*}).to_s.delete"[" #need to finish this regex to make it work 
    account_log.account_id = extract_account_id(line) 
    account_log.bytes = line.match(%r{^.*\s+HTTP.*\s+-\s+(\d+)\s+}).captures.join.to_i 
    puts "\n" 
    puts "The api request on #{account_log.date} was fromm account number #{account_log.account_id} and the bytes were #{account_log.bytes}" 
end 
0

虽然你可以采取类方法的方法,似乎有更多的事情发生。

你应该把提取逻辑放在一个方法本身,而不是让它在你的班级聚集。然后在课程外部,有一个AccountLog实例,您可以在其中调用日志和帐户ID提取方法。那时你可以用这些值做点什么。

类或不是类的方法是一个细节,我们可以探讨之后,我觉得类更清洁一点。