2017-03-06 35 views
0

下面的代碼是除了'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

回答

3

您應該使用each_with_index而不是each得到index

+0

哦我的!!有用!非常感謝!!我爲你投票。我想'索引'不適用於'每個',但只與'each_with_index'? – gin85

+0

是的,'each'只接收1個參數,即值。此外,如果這可以解決您的問題,請將其標記爲正確答案 – MaicolBen

+0

對不起,我在這裏很新,我怎麼能標記爲'正確答案'? – gin85

0

正如你可以看到the documentation of Array#each,只產生一個參數塊:

each { |item| block } → ary 
#  ↑↑↑↑↑↑ 

然而,您的區塊需要兩個參數:

words.each {|word, index| 
#   ↑↑↑↑↑↑↑↑↑↑↑↑↑ 

由於each只有收益率作爲塊的一個參數,第二個參數將始終爲nil。 (除非元素恰好是Array,那麼word將被綁定到數組的第一個元素,而index將被綁定到第二個。)並且由於index始終爲nil,因此它永遠不會等於0,因此永遠不會進入第一個分支有條件的。

有,然而,這實際上產生了兩個參數是塊的其他的迭代法,元素和它的指數,它被稱爲Enumerable#each_with_index

words.each_with_index {|word, index| 
#   ↑↑↑↑↑↑↑↑↑↑↑ 

這就是你需要改變,以使你的代碼工作。

+0

這是很好的友好的解釋!謝謝你:-) – gin85

0

這裏,另一種不使用eacheach_with_index的方式。

def titleize (word) 
    littleWords = ["and", "the", "over", "or"] 
    words = word.split(" ") 
    words[0].capitalize + " " + words[1..-1].map do |w| 
     littleWords.include?(w) ? w : w.capitalize 
    end.join(" ") 
end 
+0

非常感謝你!我試圖將此代碼應用於其他代碼之一。酷:-) – gin85

0

您可以使用String#gsub正則表達式和塊。

def titlesize(str, little_words) 
    str.gsub(/[[:alpha:]]+/) { |w| little_words.include?(w) & 
    (Regexp.last_match.begin(0) > 0) ? w : w.capitalize } 
end 

little_words等於[ 「的」 「和」, 「該」, 「上方」,]數組,

titlesize "the days of wine and roses", little_words 
    #=> "The Days of Wine and Roses" 

參見Regexp::last_matchMatchData#beginRegexp.last_match可以被全局變量$~替代。

相關問題