Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby实例变量语法约定_Ruby_Coding Style_Syntax - Fatal编程技术网

Ruby实例变量语法约定

Ruby实例变量语法约定,ruby,coding-style,syntax,Ruby,Coding Style,Syntax,在实例方法中引用实例变量的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

在实例方法中引用实例变量的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
?设置变量时使用
self.q

self.q = 'Some value.'
puts q
do_something_with_variable(q)
q
用于获取变量

self.q = 'Some value.'
puts q
do_something_with_variable(q)
当然,这些纯粹是惯例。在获取变量时,您可以随时用
self.q
替换
q
(尽管建议一致性)


关于使用
@q

,我发现非常有启发性。Ruby使用实例变量和访问器方法(使用语法糖看起来像是直接访问属性)的全部原因是为了重构类和接口的外部使用者

puts musicObj.minutes
不必知道您内部是否有:

attr_accessor :minutes

同样的rational同样适用于您自己的代码。如果您有一个包含100个方法的类,这些方法都引用了
@minutes
,然后您决定确实应该存储
@seconds
,那么您需要更改100个方法。另一方面,如果您使用了
minutes
(您的“方法之一”),那么您的任何方法都不需要更改

使用方法调用表示法而不是直接访问实例变量会对性能造成小的影响。如果速度是关键的,你可能需要考虑直接访问;否则,我鼓励您吃自己的狗粮,并使用您公开的任何可公开访问的接口(如果存在)


而且,正如@Alex所回答的,当调用“setter”方法时,您必须使用
self.foo=42
符号,因为
foo=42
将始终设置一个局部变量。

@q
初始化
中设置变量时似乎起作用。是否需要
self.q
?@MrMusic:
@q
也适用于设置。毕竟,这就是实例变量本身。好的一点(+1)。但你的例子有点糟糕。如果您只使用访问器,那么您的示例中的
self.minutes=
将只存储分辨率为60:-)@undur\u的秒数,如果您传入的是浮点数分钟,则不存储秒数;e、 g.
def分钟=(m)@秒=(m*60)。整轮;结束
类似问题: