2014-03-06 32 views
-2

所以我正在爲ruby dev bootcamp做準備工作,並且需要創建一個能夠使標題大寫的程序。我目前的代碼使用#capitalize!,但是當一個數字包含在字符串中時,它被省略了。紅寶石如何使用#capitalize!並保留字符串編號

words = title.split(' ') 
words.map! do |word| 
    if %w(a aboard about above absent across after against along alongside amid amidst among amongst an and around as aslant astride at 
    athwart atop barring before behind below beneath beside besides between beyond but by despite down during except for from in inside 
    into like mid minus near next nor notwithstanding of off on onto opposite or out outside over past per plus regarding round save 
    since so than the through throughout till times to toward towards under underneath unlike until up upon via vs. when with within 
    without worth yet).include?(word) && word != words[0] 
    word 
    else 
    word.capitalize! 
    end 

所以當what I wish I knew when I was 20輸入我得到What I Wish I Knew When I Was 有什麼建議?

+0

你能舉個例子嗎? 'a ='hello3'; a.capitalize!'將'a'變成'Hello3'。這對你來說有什麼不同? – Matt

回答

5

使用capitalize而不是capitalize!

順便說一句,如果您的word != words[0]的意圖是如果它不是第一個單詞,而是將任何單詞放在列表中,那麼您就錯了。它不這樣工作。原因留給你作爲家庭作業。

+0

因爲'20.capitalize!'是'nil'。 +1 –

+2

+1旁註:如果'word ='A''也會返回'nil',因爲像數字一樣,這個詞沒有改變。 – Matt

0

只是改變word.capitalize!word.capitalize! || word

"20".capitalize! #=> nil 
"20".capitalize! || "20" #=> 20 
+1

爲什麼工作太多......?非OP版本就足夠了,因爲OP使用'#map'。 –

+0

點好評+1 @sawa。 – engineersmnky