A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.翻譯:直接看下面需要過的測試,會給你兩個參數,第二個不一定會給。
1.第一個參數內的所有字元都要轉換(開頭大寫,其他字小寫)
2.如果第二個參數有給的話,用來跟第一個參數比對,字元有一樣的話(不分大小寫)整個字元都變成小寫。
3.最後,前面做完任何轉換,第一個參數的第一個字元的開頭字一定要是大寫
def title_case(title, minor_words = '')
end
RSpec.describe "Title Case" do
it "Example cases" do
expect(title_case('')).to eq('')
expect(title_case('a clash of KINGS', 'a an the of')).to eq('A Clash of Kings')
expect(title_case('THE WIND IN THE WILLOWS', 'The In')).to eq('The Wind in the Willows')
expect(title_case('the quick brown fox')).to eq('The Quick Brown Fox')
end
end
def title_case(title, minor_words = '')
return '' if title == ''
return title.split(" ").map(&:capitalize).join(" ") if title.length != 0 && minor_words == ''
if minor_words.length != 0
minor = minor_words.split(" ").map(&:capitalize)
end
result = title.split(" ").map(&:capitalize).map do |t|
minor.each do |m|
if t == m
t = t.downcase
break
end
end
t
end
result[0] = result[0].capitalize
result.join(" ")
end
def title_case(title, minor_words = '')
title.capitalize.split().map{|a| minor_words.downcase.split().include?(a) ? a : a.capitalize}.join(' ')
end