2014-05-17 57 views
0

我正在研究一種方法,用於大寫除非其中一個小單詞被傳入的句子的每個單詞的第一個字母。 (句子中的這第一個字總是不管大寫)Titileize方法在標題中大寫字母大寫

我有以下幾點:

def titleize(t) 
little = ["over", "the", "and"] 
q = t.split(" ") 
u = [] 

    q.each do |i| 
     p = i.split("") 
     p[0] = p[0].upcase 
     r = p.join("") 
      if i == q[0] 
       u.push(r) 
      elsif i == little[0] || i == little[1] || i == little[2] 
       u.push(i) 
      else 
       u.push(r) 
      end 
     end 
    s = u.join(" ") 
    return s 

end 

當我通過試運轉我,我得到:

 Failure/Error: titleize("the bridge over the river kwai").should == "The Br 
    idge over the River Kwai" 
     expected: "The Bridge over the River Kwai" 
     got: "The Bridge over The River Kwai" (using ==) 

爲什麼句子中的第二個「the」被大寫?

+0

側面說明,考慮使用描述性的變量名,比如'句子,','words','characters'而不是't','q','p'。爲了可讀性做了很多工作。 –

+0

您已選擇@ sawa的答案,但未選中它。你沒有任何迴應的義務,但我提到這是你的新成員,可能沒有意識到你可以調高你選擇的答案。 –

回答

0

因爲q[0]"the",所以當i"the",它滿足以下條件:

i == q[0] 

一個更好的辦法來做到這一點是:

Little = %w[over the and] 
def titleize s 
    s.gsub(/\w+/) 
    .with_index{|w, i| i.zero? || Little.include?(w).! ? w.capitalize : w} 
end 

titleize("the bridge over the river kwai") 
# => "The Bridge over the River Kwai" 
+0

那麼,爲什麼它不推動我,它的推動我大寫...... – user3597950

+0

因爲你在這種情況下有'u.push(r)'。 – sawa

+0

我說的是第二個不是第一個 – user3597950

0

編輯:下面是我原來的建議,另一種解決方案,其代碼:

class String 
    def titleize(exclusions) 
    words = self.split.map do |word| 
     exclusions.include?(word) ? word : word.capitalize 
    end 
    words.first.capitalize! 
    words.join(" ") 
    end 
end 

string = "the bridge over the river kwai" 
exclusions = %w{ over the and } 
p string.titleize(exclusions) 
    #=> "The Bridge over the River Kwai" 

原來的答覆: 如何只大寫整個字符串中的每個單詞,然後使用GSUB與他們的小寫版本來替代的話在適當的時候?

string = "the bridge over the river kwai" 
exclusions = %w{ over the and } 
p string.split.map(&:capitalize).join(" ").gsub(/(?<!^)(#{exclusions.join("|")})/i) {|word| word.downcase} 
    #=> "The Bridge over the River Kwai" 
+0

有人可以解釋這個downvote嗎? – user3597950

+0

它不回答這個問題。 – sawa

+0

謝謝我能解決它! – user3597950

0

上面的一個變種:

def titleize(s) 
    s.sub(/\w+/) { |w| w.capitalize } 
    .gsub(/\w+/) { |w| Little.include?(w) ? w : w.capitalize } 
end 

試試:

s =<<THE_END 
to protect his new shoes from the rain, a man stood atop a stack of 
newspapers in Times Square. When the newsstand's proprietor asked 
if he realized what he was standing on, he replied, "of course, 
these are the times that dry men's soles". 
THE_END 

Little = ["the", "and", "a", "on", "to", "from", "in"] 

titleize(s) 
    #=> "To Protect His New Shoes from the Rain, a Man Stood Atop a Stack Of \n 
    # Newspapers in Times Square. When the Newsstand'S Proprietor Asked\n 
    # If He Realized What He Was Standing on, He Replied, \"Of Course,\n 
    # These\nAre the Times That Dry Men'S Soles\".\n"