奇怪的是,我在互联网上找不到任何关于这方面的信息。
我有一个类方法,它应该向哈希添加一些东西。例如:
def add_file(name, file)
@files[name] = file
end
如果我用相同的方法用@files = Hash.new
初始化散列,每次我试图向它添加东西而不是添加东西时,它都会生成一个全新的散列。但当我将初始化从类主体中的方法中移出时,它会出现一个错误:
in 'add_file': undefined method '[]=' for nil:NilClass (NoMethodError)
那么,我该如何初始化哈希,以便稍后在另一个方法中使用它呢。
请保持简单的解释,我是新来的。谢谢
我不会总是检查add
/etc方法中是否存在哈希。
这需要始终检查任何期望的哈希。
如果类是作为文件存储的包装器,那么只有在实例化时创建它才有意义,例如
class SomeClass
def initialize
@files = {}
end
def add_file(name, file)
# Etc.
end
end
它在类主体中的哈希创建失败,因为它位于类,而不是实例级别,例如
class NotWhatYouExpect
@foo = "bar"
end
@foo
是类实例变量;它属于类NotWhatYouExpect
,而不是它的实例。
这看起来像是一个实例方法,而不是类方法。不同之处在于,它是一个可以在类的特定实例上调用的方法。
在任何情况下,你都可以做
def add_file(name, file)
@files ||= {}
@files[name] = file
end
这将把@files初始化为空散列,除非实例变量存在(并且不是false)
试试这个:
def add_file(name, file)
@files || = {} #Checking if hash is initialized. If not initializing
@files[name] = file #adding element
@files #returning hash
end
这将添加一个新的密钥val对,并返回完整的散列。
在类声明(而不是方法内部)内初始化实例成员(以@
开头的变量)时,该成员将初始化为类的成员,而不是其实例。
要为每个实例初始化一个成员,需要在initialize方法中进行:
class MyTest
@class_hash = Hash.new
def initialize()
@instance_hash = Hash.new
end
def class_hash
@class_hash
end
def instance_hash
@instance_hash
end
def self.class_hash
@class_hash
end
end
puts MyTest.new.class_hash
# => nil
puts MyTest.new.instance_hash
# => {}
puts MyTest.class_hash
# => {}