0
試圖瞭解如何使用setter methods
爲什麼我在這裏失敗?我不明白我做錯了什麼。有人可以解釋嗎?謝謝。Ruby中的類,對象和setter方法?
class Book
def title=(title)
@title = title.capitalize
end
end
Rspec的
describe Book do
before do
@book = Book.new
end
describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
@book.title.should == "Inferno"
end
end
end
測試失敗:
Book title should capitalize the first letter Failure/Error: @book.title.should == "Inferno"
NoMethodError:
undefined method `title' for #<Book:0x00000104abd538 @title="Inferno"> # ./ct.rb:865:in `block (3 levels) in <top (required)>'
是有道理的。問題:爲什麼這不起作用? '@title = title.split.each {| w | w.capitalize} .join(「」)'預計:「Stuart Little」,但會得到:「stuart little」。爲什麼不在這裏利用工作? – fyz
這是一個完全不同的問題,但在這裏你會發現:'each'遍歷一個集合,但不會修改它。使用'map'代替:'@title = title.split.map(&:capitalize).join('')' – Agis
@Agis:看起來你正在追求飢餓。做得好! – Bala