下面的代碼是除了'littleWords'和標題的第一個單詞之外的所有單詞。 (即使它屬於littleWords,第一個單詞應該大寫。)ruby大寫不適用於標題的第一個單詞
def titleize (word)
littleWords = ["and", "the", "over", "or"]
words = Array.new
words = word.split(" ")
titleWords = Array.new
words.each {|word, index|
if index == 0
word = word.capitalize
else
unless littleWords.include?(word)
word = word.capitalize
end
end
titleWords << word
}
return titleWords.join(" ")
end
和測試代碼如下。
it "does capitalize 'little words' at the start of a title" do
expect(titleize("the bridge over the river chao praya")).to eq("The Bridge over the River chao praya")
end
但它一直以大寫第一個「的」作爲剛「的」,而不是「的」。我想知道我的代碼的哪個部分是錯誤的。幫我... TT
哦我的!!有用!非常感謝!!我爲你投票。我想'索引'不適用於'每個',但只與'each_with_index'? – gin85
是的,'each'只接收1個參數,即值。此外,如果這可以解決您的問題,請將其標記爲正確答案 – MaicolBen
對不起,我在這裏很新,我怎麼能標記爲'正確答案'? – gin85