class Book
attr_accessor :author
attr_reader :title
attr_reader :comments
def initialize(author, title)
@author = author
@title = title
@comments = []
end
end
book = Book.new("Chuck Palahniuk", "Fight Club")
book.comments << "#{book.title} was a good book"
book.comments.each do |p|
puts p
end
# Fight Club was a good book
如果comments方法只是一個attr_reader而不是attr_writer,爲什麼< <追加工作?是因爲它繞過了attr_writer的=號嗎?確實會有<< sign bypass =登入ruby嗎?
這是一個準確的解釋。我會補充說,你可以通過調用['freeze']來避免修改數組的內部狀態(即使用'<<'方法)(http://ruby-doc.org/core-2.1.5/Object.html #method-i-freeze)方法就可以了。 –
@GabrieldeOliveira請注意使用_freeze _...,除非您真的需要它.. –
@Arup,請詳細說明。 –