如何为nil类错误调试未定义的方法?

时间:2012-02-08 15:49:17

标签: ruby rubygems

我正在尝试使用cardmagic分类器gem创建一个分类器。这是我的代码:

require 'classifier'

classifications = '1007.09', '1006.03'
traindata = Hash["1007.09" => "ADAPTER- SCREENING FOR VALVES VBS", "1006.03" => "ACTUATOR- LINEAR"]

b = Classifier::Bayes.new classifications

traindata.each do |key, value|  
b.train(key, value)
end 

但是当我运行这个时,我收到以下错误:

Notice: for 10x faster LSI support, please install http://rb-gsl.rubyforge.org/
c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:27:in `block in train': undefined method `[]' for nil:NilClass (NoMethodError)
  from c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:26:in `each'
  from c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:26:in `train'
  from C:/_Chris/Code/classifier/smdclasser.rb:13:in `block in <main>'
  from C:/_Chris/Code/classifier/smdclasser.rb:11:in `each'
  from C:/_Chris/Code/classifier/smdclasser.rb:11:in `<main>'

这是gem代码的来源:

# Provides a general training method for all categories specified in Bayes#new
# For example:
#     b = Classifier::Bayes.new 'This', 'That', 'the_other'
#     b.train :this, "This text"
#     b.train "that", "That text"
#     b.train "The other", "The other text"
def train(category, text)
  category = category.prepare_category_name
  text.word_hash.each do |word, count|
    @categories[category][word]     ||=     0
    @categories[category][word]      +=     count
    @total_words += count
  end
end

我迷失了去哪里解决这个错误,我应该采取的下一步是什么?

1 个答案:

答案 0 :(得分:5)

Classifier::Bayes.new需要一个爆炸的值数组,而不是一个参数。例如,请注意示例代码使用:

b = Classifier::Bayes.new 'This', 'That', 'the_other'

而不是:

b = Classifier::Bayes.new ['This', 'That', 'the_other']

传入classifications数组的splat版本,它应该可以工作:

b = Classifier::Bayes.new *classifications