Ruby 实例变量语法约定
在实例方法中引用实例变量的 Ruby 约定是什么?
考虑以下变化:
def MyClass
attr_accessor :q
def initialize(z)
@q = z
end
def method_one
puts q
end
def method_two
puts @q
end
def method_three
puts self.q
end
end
首选 q
、@q
或 self.q
哪种约定?
What's the Ruby convention for referring to instance variables inside an instance method?
Consider the following variations:
def MyClass
attr_accessor :q
def initialize(z)
@q = z
end
def method_one
puts q
end
def method_two
puts @q
end
def method_three
puts self.q
end
end
Which convention q
, @q
or self.q
is preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 使用实例变量和访问器方法(使用语法糖看起来就像您可以直接访问属性)的全部原因是,您可以重构您的类,而接口的外部使用者则
不需要这样做。不必知道您内部是否有:
或
同样的道理同样适用于您自己的代码。如果您有一个包含 100 个方法的类,所有方法都引用您的
@months
,然后您决定确实应该存储@seconds
,那么您将需要更改 100 个方法。另一方面,如果您使用了分钟(您的“method_one”),则您的任何方法都不需要更改。使用方法调用表示法而不是直接访问实例变量会对性能造成一些影响。如果速度至关重要,您可能需要考虑直接访问;否则,我鼓励您吃自己的狗粮并使用您公开的任何可公开访问的接口(如果存在)。
并且,正如 @Alex 回答的那样,在调用“setter”方法时,您必须使用
self.foo = 42
表示法,因为foo = 42
将始终设置一个而是局部变量。The whole reason that Ruby uses instance variables and accessor methods (with syntax sugar to look like you're getting direct access to properties) is so that you can refactor your classes and external consumers of your interface
don't have to know if you internally have:
or
This same rational applies equally well to your own code. If you have a class with 100 methods that all reference your
@minutes
, and then you decide that you really should be storing@seconds
you will need to change 100 methods. On the other hand, if you had usedminutes
(your "method_one") instead, none of your methods would need to change.There is a small performance hit for using the method-invocation notation instead of directly accessing the instance variable. If speed is critical you may want to consider direct access; otherwise, I encourage you to eat your own dog food and use any publicly-accessible interfaces you expose, when they exist.
And, as @Alex answered, you must use the
self.foo = 42
notation when invoking a 'setter' method, asfoo = 42
will always set a local variable instead.self.q
用于设置变量,而
q
用于获取变量当然,这些纯粹是约定。当获取变量时,您可以随时用
self.q
替换q
(尽管建议保持一致性)。我发现此讨论对于使用
@q
很有启发。self.q
is used when setting the variablewhereas
q
is used when getting the variableOf course, these are purely conventions. You can substitute
self.q
forq
when getting the variable whenever you like (although consistency is recommended).I find this discussion quite enlightening with regards to using
@q
.