在Java中,有一个“this”函数指向它的方法。 Ruby 中有类似的东西吗?例如,有没有:
def method
this.method
end
等价的是self
。这也是隐含的。所以self.first_name
是相同的first_name
除非你正在做作业,否则在课堂上。
class Book
attr_reader :first_name, :last_name
def full_name
# this is the same as self.first_name + ", " + self.last_name
first_name + ", " + last_name
end
end
进行作业时,您需要使用self
明确地,因为 Ruby 无法知道您是否正在分配一个名为first_name
或分配给instance.first_name
.
class Book
def foo
self.first_name = "Bar"
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)