在可能的情況下,有一種約定可以在其實例變量上引用對象的屬性。 Practical Object-Oriented Design in Ruby說:在object.initialize中,最好使用self。在@?
始終包裹實例變量的訪問方法,而不是直接 參考變量...
這用一個例子,我已經轉述:
class Gear
attr_reader :chainring, :cog
...
def ratio
# this is bad
# @chainring/@cog.to_f
# this is good
chainring/cog.to_f
end
最常用的方法我看到來創建一個實例變量的新對象是這樣的:
class Book
attr_accessor :title
def initialize(title)
@title = title
end
end
@title=
直接訪問實例變量title
。 假設我們正在慣例,繼的「過度實例變量屬性」是它更適合使用self.title=
,which would tell the object to send itself the message title=
,從而使用該屬性寫入方法,比直接實例變量?
class Book
attr_accessor :title
def initialize(title)
self.title = title
end
end
這本書談到'屬性超過實例變量'引用讀取實例變量,但它不適用於寫?
在一些情況下'self.feature ='更優選比'@特徵=',通常在這種情況下,當分配到'self.'殼做更多actiona然後只是分配。第二,在這裏:https://github.com/3aHyga/ruby-style-guide你可以看到,良好的作風'self.feature ='是encontered只有一次,當複雜的任務(這意味着不僅僅是assisnment到發生實例變量)。在閱讀總是使用像'feature ==「值」''的結構的情況下 –