Ruby:在另一个类的类方法中访问一个类的类实例变量
我正在开发一个 ruby 程序并遇到了以下问题。
我有两个类 AClass 和 BClass 如下:
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
def BClass.build(aclass)
bvalue = aclass.avar
....
end
end
当我运行时:
aclass = AClass.new
puts aclass.avar
bclass = BClass.build(aclass)
前两行工作正常。 aclass 被初始化并且 avar 被输出到屏幕上,但是第三行产生了错误。我似乎 BClass 构建方法无法访问 AClass 实例变量。我需要做什么才能使这项工作成功。我认为 attr_accessor 将使我能够访问 AClass 实例变量。预先感谢您的意见。
I am working on a ruby program and have run into the following problem.
I have two classes AClass and BClass as follows:
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
def BClass.build(aclass)
bvalue = aclass.avar
....
end
end
When i run:
aclass = AClass.new
puts aclass.avar
bclass = BClass.build(aclass)
The first two lines work fine. aclass is intialized and avar is put out to the screen, but the third line creates an error. I seems that the BClass build method can not access the AClass instance variable. What do I need to do to make this work. I thought the attr_accessor would enable me to access the AClass instance variables. Thanks in advance for your input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要为 BClass 创建新类型的初始值设定项,可以执行以下操作:
这将设置 bclass.bvalue = aclass.avar = 'ruby'。
If you want to create a new type of initializer for BClass, you can do the following:
This will set bclass.bvalue = aclass.avar = 'ruby'.
Mutu,你需要学习 ruby 的基础知识......你所拥有的甚至没有有效的 ruby 代码。
尝试运行这个。
在IRB中
Mutu, you need to learn the basics of ruby... what you have there is not even valid ruby code.
try running this.
in irb