在Ruby中,在类的实例方法中,我们使用getter by
foo
Run Code Online (Sandbox Code Playgroud)
我们用一个二传手
self.foo = something
Run Code Online (Sandbox Code Playgroud)
一个人不需要有一个self.而另一个没有,有没有办法使它们看起来更相似,而不是像self.foogetter 这样的东西,因为它看起来也很冗长.
(更新:请注意,getter和setter可能只是获取或设置一个实例变量,但它们也可能会做很多工作,例如进入数据库并检查是否存在记录,如果没有,则创建它等)
Mat*_*ira 10
由于本地范围优先,当您说foo = something,foo将创建一个局部变量并分配其内容something.
您可以编写foo以便使用getter的原因是因为当Ruby无法找到具有该名称的变量时,它将在范围内向上移动,并且最终将找到该方法.
如果有一个与getter方法同名的局部变量,Ruby将使用其值:
class Foo
attr_accessor :foo
def initialize
@foo = :one
end
def f
foo = :two
foo
end
end
Foo.new.f
# => :two
Run Code Online (Sandbox Code Playgroud)
为了清楚地表明您想要访问setter,您必须编写self.foo = something.这将告诉Ruby你想用as参数foo=在self对象上执行方法something.
如果您愿意违反约定,可以使用jQuery样式编写setter,使用相同的getter和setter方法,具体取决于它是否有参数:
def foo *args
return @foo if args.empty?
@foo = args.first
end
# => nil
foo
# => nil
foo(:bar) # foo = :bar
# => :bar
foo
# => :bar
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
741 次 |
| 最近记录: |