私は現在、Test First の rspec チュートリアルを行っており、Pig_Latin の問題に関する質問があります。
具体的には、文字列の範囲について知りたいです。ここに私のコードのセクションがあります:
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
いつものように、コードをより効率的にするためのヒントをいただければ幸いです (しかし、私にとって最も重要なことは、文字列範囲が機能しない理由を理解することです)。ありがとう。