在Ruby中实例化一个类并填充实例变量
问题描述:
我有一种感觉,我在这里错过了很简单的东西。我有一个与外部服务相关的课程。我想通过调用create方法或find方法来实例化它。这两种方法都会通过创建节点或找到它来使用散列填充实例变量“@node”。在Ruby中实例化一个类并填充实例变量
我
class GenreInfluence
@@neo ||= Neography::Rest.new()
attr_accessor :node
def initialize
end
def self.create
@node = @@neo.create_node
self.new
end
def self.find(node_id)
@node = @@neo.get_node(node_id)
self.new
end
def get_hash
@node
end
如果我注释掉这是怎么回事,我可以看到它的创建类,并得到正确的哈希回不过:
theInstance = GenreInfluence.find(20)
theInstance.get_hash
就返回nil。为什么散列没有存储在实例变量中!?
答
您不能在非实例(静态或类)方法中设置实例变量。此外,你的两个方法都返回self.new
,这有效地返回了没有设置实例变量的类的新实例。
如何以下,创建静态类的方法类的新实例,设置该实例变量,然后返回它(而不是返回self.new
):
class GenreInfluence
@@neo ||= Neography::Rest.new()
attr_accessor :node
def initialize
end
def self.create
influence = self.new
influence.node = @@neo.create_node
influence
end
def self.find(node_id)
influence = self.new
influence.node = @@neo.get_node(node_id)
influence
end
def get_hash
@node
end
end
答
您正在从查找方法返回self.new
。这是带有一组实例变量的GenreInfluence
的新实例。
答
如何
class GenreInfluence
@@neo ||= Neography::Rest.new()
attr_accessor :node
def initialize(node_id = nil)
if (node_id.nil?) then
@node = @@neo.create_node
else
@node = @@neo.get_node(node_id)
end
end
def find(node_id)
@node = @@neo.get_node(node_id)
end
def get_hash
@node
end
end
然后
theInstance = GenreInfluence.new()
theInstance.get_hash
theInstance1 = GenreInfluence.new(20)
theInstance1.get_hash
theInstance2 = GenreInfluence.new()
theInstance2.get_hash
theInstance2.find(20)
theInstance2.get_hash
谢谢,这将很好地工作。有时我的大脑只是放弃了;) – Samuel 2011-03-04 06:45:06
+1打我冲。 – jdl 2011-03-04 06:47:27