ruby 我应该使用 self.或者 @ [英] ruby should I use self. or @
问题描述
这是我的红宝石代码
class Demo
attr_accessor :lines
def initialize(lines)
self.lines = lines
end
end
在上面的代码中我可以使用
In the above code I could have used
@lines = lines
我经常看到人们在 initialize 方法中使用 @.在这两者中是否有首选的方法?为什么?
Mostly I see people using @ in initialize method. Is there a preferred way of doing among these two and why?
推荐答案
当您使用 @lines
时,您正在访问实例变量本身.self.lines
实际上是通过了类的lines
方法;同样,self.lines = x
通过 lines=
方法.所以当你想直接访问变量时使用@
,当你想通过方法访问时使用self.
.
When you use @lines
, you are accessing the instance variable itself. self.lines
actually goes through the lines
method of the class; likewise, self.lines = x
goes through the lines=
method. So use @
when you want to access the variable directly, and self.
when you want to access via the method.
要直接回答您的问题,通常您想直接在 initialize
方法中设置实例变量,但这取决于您的用例.
To directly answer your question, normally you want to set the instance variables directly in your initialize
method, but it depends on your use-case.
这篇关于ruby 我应该使用 self.或者 @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!