为什么这个实例变量突然有一个nil的值?

时间:2014-01-05 03:03:31

标签: ruby

使用Ruby 1.9.2,我希望我的DictionaryPresenter类扩展Enumerable,但我在each方法上收到错误。错误是dictionarynil,即使它已在initialize中正确分配。

我认为这与使用dictionary的属性方法有关,而不是直接使用实例变量@dictionary。我已经读过你应该尝试在可能的情况下用属性方法替换实例变量use,这就是我所做的。

class DictionaryPresenter
  include Enumerable
  attr_accessor :dictionary
  private :dictionary
  def initialize(collection)
    dictionary = dictionary_hash
    collection.each do |element|
      dictionary[element[0].capitalize] << element
    end
    p 'dictionary has been filled. it is'
    p dictionary
  end
  def dictionary_hash
    ('A'..'Z').reduce({}) do |hash, letter|
      hash[letter] = []
      hash
    end
  end
  def each(&blk)
    p 'in each'
    p dictionary
    dictionary.each(&blk)
  end
end
p DictionaryPresenter.new(['abba', 'beegees']).map{ |a| a }

输出

"dictionary has been filled. it is"
{"A"=>["abba"], "B"=>["beegees"], "C"=>[], "D"=>[], "E"=>[], "F"=>[], "G"=>[], "H"=>[], "I"=>[], "J"=>[], "K"=>[], "L"=>[], "M"=>[], "N"=>[], "O"=>[], "P"=>[], "Q"=>[], "R"=>[], "S"=>[], "T"=>[], "U"=>[], "V"=>[], "W"=>[], "X"=>[], "Y"=>[], "Z"=>[]}
"in each"
nil
anki.rb:22:in `each': undefined method `each' for nil:NilClass (NoMethodError)
    from anki.rb:25:in `map'
    from anki.rb:25:in `<main>'

1 个答案:

答案 0 :(得分:1)

在构造函数中,您必须使用self.dictionary = dictionary_hash而不是dictionary = dictionary_hash

您的版本dictionary = ...在构造函数中创建 local 变量,并为其赋值;它实际上并不使用您定义的attr_accessor。对于类方法中的所有变量赋值都是如此。如果您想使用setter(您使用def field=attr_accessor :field明确定义的方法),则需要使用self.field =而不是field =。< / p>