Мне нужно загладить каждое слово в названии книги для моего кода. У меня возникают проблемы с итерацией каждого элемента массива и заглавной буквы первой буквы. Я действительно не вижу, что я делаю неправильно. Любая помощь будет принята с благодарностью.Заглавные буквы книг без .titleize
class Title
attr_accessor :string
def initialize(string)
@string = string
end
def fix
@string.downcase!
new_array = []
if @string.include?(" ")
new_array << @string.split(" ")
new_array.map {|word| word.capitalize}
new_array.join(" ")
else
@string.capitalize!
end
end
end
Характеристики:
describe "Title" do
describe "fix" do
it "capitalizes the first letter of each word" do
expect(Title.new("the great gatsby").fix).to eq("The Great Gatsby")
end
it "works for words with mixed cases" do
expect(Title.new("liTTle reD Riding hOOD").fix).to eq("Little Red Riding Hood")
end
it "downcases articles" do
expect(Title.new("The lord of the rings").fix).to eq("The Lord of the Rings")
expect(Title.new("The sword And The stone").fix).to eq("The Sword and the Stone")
expect(Title.new("the portrait of a lady").fix).to eq("The Portrait of a Lady")
end
it "works for strings with all uppercase characters" do
expect(Title.new("THE SWORD AND THE STONE").fix).to eq("The Sword and the Stone")
end
end
end
Объясните фактическую ошибку или проблему, с которой вы сталкиваетесь. – Beartech
У вас есть одна проблема: 'new_array << @ string.split (" ")', вы разделяете строку и затем нажимаете весь этот массив на 'new_array'. Поэтому 'new_array' - это одноэлементный массив, содержащий массив. Вот почему вы, вероятно, получаете ошибку, пытающуюся использовать '.capitalize' на массиве – dwenzel