2013-10-02 68 views
0

我目前正在做Test First的rspec教程,並且有一個與Pig_Latin問題有關的問題。Ruby:拉丁語翻譯器中的字符串範圍

具體我想知道關於字符串範圍。這裏是我的代碼段:

if phonemes.include?(word[0]) && phonemes.include?(word[1]) && phonemes.include?(word[2]) 
<do something> 
end 

相反,我嘗試了上面的:

if phonemes.include?(word[0..2]) # i added that character to the list of phonemes 
    <do something>     # e.g. if the word is school i added "sch" to 
end        # the array called phonemes 

然而,即使"sch"phonemes不工作,word[0..2] == "sch"

我的問題是爲什麼我可以不使用字符串範圍來操縱結果。 (我會後我完整的代碼底部的情況下,這是不清楚)

代碼(工作正在進行中):

def translate(string) 
array = string.split(" ") 
alphabet = ("a".."z").to_a 
vowels = ["a", "e", "i", "o", "u"] 
phonemes = alphabet - vowels 
phonemes << ["qu", "sch", "thr"] 
result = [] 
array.each do |word| 
    if vowels.include?(word[0]) 
     result << (word + "ay") 
    elsif phonemes.include?(word[0..1]) 
     result << "do something" 
    elsif phonemes.include?(word[0]) && phonemes.include?(word[1]) && phonemes.include?(word[2]) 
     result << (word[3..-1] + (word[0..2] + "ay")) 
    elsif phonemes.include?(word[0]) && phonemes.include?(word[1]) 
     result << (word[2..-1] + (word[0..1] + "ay")) 
    elsif phonemes.include?(word[0..1]) 
     result << "do something else" 
    elsif phonemes.include?(word[0]) 
     result << (word[1..-1] + (word[0]+ "ay")) 
    end 
end 
return result.join(" ") 
end 

一如既往的提示,使代碼更高效,將不勝感激(但最對我來說重要的是要理解爲什麼字符串範圍不工作)。 謝謝。

回答

1

您的語句phonemes << ["qu", "sch", "thr"]將該數組添加爲phonemes的最後一個元素,這就是include?失敗的原因。 <<運算符用於將單個元素添加到陣列。如果要將該數組中的所有元素添加到phonemes,則可以使用+=運算符。

+0

太棒了!這樣做很完美,非常感謝你! –

1

這不是您的主要問題的答案,但您需要提示以改善您的代碼。我建議你考慮使用一個案例陳述,你有很長的if-else。它使其更具可讀性並減少重複。事情是這樣的:

result << case 
    when vowels.include?(word[0]) 
    word + "ay" 
    when phonemes.include?(word[0..1]) 
    "do something" 
    when phonemes.include?(word[0]) && phonemes.include?(word[1]) 
    if phonemes.include?(word[2]) 
     word[3..-1] + word[0..2] + "ay" 
    else 
     word[2..-1] + word[0..1] + "ay" 
    end 
    when phonemes.include?(word[0..1]) 
    "do something else" 
    when phonemes.include?(word[0]) 
    word[1..-1] + word[0]+ "ay" 
    else 
    "do something else or raise an error if you reach this point." 
end 

我沒有在你的代碼仔細一看,但我沒有,你有兩次phonemes.include?(word[0..1])通知,所以第二個永遠不會被執行。

+0

哈哈是啊,我看到了。我一直在重寫它,並保存了我一直困惑的舊版本。我剛剛完成了這個問題(因爲我剛剛完成,所以沒有真正關注它的效率),但是我清理了那些東西。我非常感謝答覆,我將在發言時審視這些答覆。澄清'when'和'if'之間的區別以及'result << case'是什麼。更具體地說'case' –

+1

@Sai'when'是與'case'語句一起使用的關鍵字。 'case'返回一個值,取決於哪個'when'適用。在這裏'case'返回一個值,將被附加到'result',就像你在代碼中做的那樣。查看案例的文檔。 –

+0

好的非常感謝你的澄清 –