在Ruby中,什么时候应该使用self。 在你的课程?
你self.property_name
在Ruby中使用self.property_name
?
在调用类的mutator时使用self。 例如,这不起作用:
class Foo attr_writer :bar def do_something bar = 2 end end
问题是’bar = 2’创建了一个名为’bar’的局部变量,而不是调用由attr_writer创建的方法’bar =’。 但是,一点点self
会解决它:
class Foo attr_writer :bar def do_something self.bar = 2 end end
self.bar = 2
根据需要调用方法bar=
。
您也可以使用self来调用与本地变量同名的阅读器:
class Foo attr_reader :bar def do_something bar = 123 puts self.bar end end
但通常最好避免给出一个与访问者同名的局部变量。
self
引用当前对象。 这适用于许多用途:
在当前对象上调用方法
class A def initialize val @val = val end def method1 1 + self.method2() end def method2 @val*2 end end
这里运行A.new(1).method1()
将返回3
。 self
的使用在这里是可选的 – 以下代码是等效的:
class A def initialize val @val = val end def method1 1 + method2() end def method2 @val*2 end end
为此目的, self
不是多余的 – 运算符重载使其成为必要:
class A def initialize val @val = val end def [] x @val + x end def method1 y [y] #returns an array! end def method2 y self.[y] #executes the [] method end end
这显示了如果要调用当前对象的[]
方法,必须如何使用self。
引用属性
您可以使用attr_accessor
和co生成读取和写入实例变量的方法。
class A attr_accessor :val def initialize val @val = val end def increment! self.val += 1 end end
使用self在这里是多余的,因为你可以直接引用变量,例如。 @val
。 使用A.new(1).increment!
会回来2。
方法链
你可以回归自我,提供一种称为链接的语法糖:
class A attr_reader :val def initialize val @val = val end def increment! @val += 1 self end end
这里,因为我们正在返回当前对象,所以可以链接方法:
A.new(1).increment!.increment!.increment!.val #returns 4
创建类方法
您可以使用self定义类方法:
class A def self.double x x*2 end def self.quadruple x self.double(self.double(x)) end end
这将使您能够调用A.double(2) #= 4
和A.quadruple(2) #=8
。 请注意,在类方法中, self
引用该类,因为该类是当前对象。
如何确定自我的价值
特定方法中self的当前值设置为调用该方法的对象。 通常这使用’。’ 符号。 当你运行some_object.some_method()
,self会在some_method的持续时间内绑定到some_object,这意味着some_method可以在上面提到的一种方式中使用self。
使用self
将引用程序中可访问的当前对象。 因此,在通过某种类型的attr_accessor
访问变量时使用attr_accessor
。 在必须的情况下,它可以用来代替对象中的@property。