在类方法中获取属性的值
我有一个类方法,我想在该类方法中访问属性的值,
class Run
attr_accessor :line
def self.output(options={})
station_no = options[:station]
title = options[:title]
line = self.line
station = line.stations[station_no-1]
end
end
我想访问 line
属性的值,在类方法中我无法使用 < 访问属性的值代码> self.line 。所以请建议我如何访问。
i have a class method where i want to access the value of an attribute
class Run
attr_accessor :line
def self.output(options={})
station_no = options[:station]
title = options[:title]
line = self.line
station = line.stations[station_no-1]
end
end
within this class method i want to access value of line
attribute and within class method i can't access the value of an attribute using self.line
. So please suggest me how i can access.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类方法在类上下文中执行,
line
是实例方法,您不能直接从self.output
访问它。您真的想从类方法访问实例属性吗?也许您需要的是类属性。如果是这样,您可以像这样声明它:
,并且能够在类方法中获取它的值。
如果您确实需要从类方法访问实例属性 - 将该实例作为参数传递给方法并调用它的访问器。
Class method is executed in class context and
line
is instance method, you can't directly access it fromself.output
.Do you really want to access instance attribute from class method? Maybe what you need is class attribute. If so, you can declare it like this:
, and will be able to get it's value within class method.
If you do need to access instance attribute from class method — pass that instance as argument to method and call accessor on it.