0
这是odin项目的一个练习,他们给你一个带有测试规范的文件,你必须编写程序来传递它们。Ruby类如何工作
程序的工作,但我刚开始Ruby类,我不明白为什么,如果我做了修改,我会告诉不起作用:
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
it 'should capitalize every word' do
@book.title = "stuart little"
@book.title.should == "Stuart Little"
end
describe 'should capitalize every word except...' do
describe 'articles' do
specify 'the' do
@book.title = "alexander the great"
@book.title.should == "Alexander the Great"
end
specify 'an' do
@book.title = "to eat an apple a day"
@book.title.should == "To Eat an Apple a Day"
end
end
specify 'conjunctions' do
@book.title = "war and peace"
@book.title.should == "War and Peace"
end
specify 'the first word' do
@book.title = "the man in the iron mask"
@book.title.should == "The Man in the Iron Mask"
end
end
end
end
代码
class Book
def title
@title
end
def title=(title)
@title = titlieze(title)
end
private
def titlieze(title)
stop_words = %w(and in the of a an)
title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ')
end
end
为什么,如果我写我这样的代码
class Book
def title=(title)
@title = titlieze(title)
@title
end
private
def titlieze(title)
stop_words = %w(and in the of a an)
title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ')
end
end
然后我得到这个错误:
Failure/Error: expect(@book.title).to eq("Inferno")
NoMethodError:
undefined method `title' for #<Book:0x000000017bd0a8 @title="Inferno">
Did you mean? title=
但这种方法“标题”没有定义?为什么它说不是?
所以期望(@ book.title)“我指的是方法”def标题,而当它写成“@ book.title =”inferno“”我指的是方法“def title =(title)”? – naufragio
这就是正确! – spickermann