我正在研究Odin项目的Ruby基础知识,完全沉迷于05_book_titles。标题需要大写,包括第一个单词,但不包括“小单词”(即" to "," The“等),除非它是第一个单词。除了大写之外,我不能让代码做任何事情。我是不是误用了map方法?如何才能让它在返回的标题中包含no_cap单词而不使用大写?
Ruby文件:
class Book
def title
@title
end
def title=(title)
no_cap = ["if", "or", "in", "a", "and", "the", "of", "to"]
p new_title = @title.split(" ")
p new_new_title = new_title.map{|i| i.capitalize if !no_cap.include? i}
.join(" ")
end
end一些等级库文件:
require 'book'
describe Book do
before do
@book = Book.new
end
describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
expect(@book.title).to eq("Inferno")
end
it 'should capitalize every word' do
@book.title = "stuart little"
expect(@book.title).to eq("Stuart Little")
end
describe 'should capitalize every word except...' do
describe 'articles' do
specify 'the' do
@book.title = "alexander the great"
expect(@book.title).to eq("Alexander the Great")
end
specify 'a' do
@book.title = "to kill a mockingbird"
expect(@book.title).to eq("To Kill a Mockingbird")
end
specify 'an' do
@book.title = "to eat an apple a day"
expect(@book.title).to eq("To Eat an Apple a Day")
end
end
specify 'conjunctions' do
@book.title = "war and peace"
expect(@book.title).to eq("War and Peace")
end
end
end
end结果:
Book
title
should capitalize the first letter (FAILED - 1)
Failures:
1) Book title should capitalize the first letter
Failure/Error: @book.title = "inferno"
NoMethodError:
undefined method `split' for nil:NilClass
# ./05_book_titles/book.rb:8:in `title='
# ./05_book_titles/book_titles_spec.rb:25:in `block (3 levels) in <top (required)>'
Finished in 0.0015 seconds (files took 0.28653 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./05_book_titles/book_titles_spec.rb:24 # Book title should capitalize the first letter发布于 2019-11-04 06:55:00
在中分配之前,您正在使用@title
new_title = @title.split(" ")应将其更改为title。
在title=方法的末尾,您不会将计算出的标题赋给@title。
您还需要在no_cap中添加' an‘,才能通过使用“一天吃一个苹果”作为标题的规范。
注意第一个词:
class Book
def title
@title
end
def title=(title)
no_cap = ["if", "or", "in", "a", "and", 'an', "the", "of", "to"]
new_title = title.split(' ').each_with_index.map do |x, i|
unless i != 0 && no_cap.include?(x)
x.capitalize
else
x
end
end
@title = new_title.join(' ')
end
endhttps://stackoverflow.com/questions/58685168
复制相似问题