我目前正在做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
一如既往的提示,使代碼更高效,將不勝感激(但最對我來說重要的是要理解爲什麼字符串範圍不工作)。 謝謝。
太棒了!這樣做很完美,非常感謝你! –