私はRubyの課題に取り組んでいます。テスト用の小さなプログラムを構築して、いくつかの単語やフレーズをブタのラテン語に翻訳しています。forループまたはwhileループが3回目と4回目の繰り返しで機能しない
まず、私が今までに得たコードを投稿させてください。
#method to determine if a vowel is a letter
def is_vowel(letter)
vowels = ['a', 'e', 'i', 'o', 'u']
if vowels.include?(letter)
true
else
false
end
end
def cut_and_paste(consonants, word)
word = "#{word}#{consonants}ay"
word.sub!(consonants, '')
end
def translate(input)
consonants = ''
words = input.split(" ")
new_words = []
for n in 0...words.length
if words[n][0..2] == 'squ'
#handles words beginning with 'squ'
consonants = 'squ'
new_words << cut_and_paste(consonants, words[n])
elsif words[n][0..1] == 'qu'
#handles words beginning with 'qu'
consonants = 'qu'
new_words << cut_and_paste(consonants, words[n])
elsif is_vowel(words[n][0])
#handles words beginning with a vowel
new_words << words[n] + 'ay'
else
i = 0
#check each letter until vowel
while is_vowel(words[n][i]) == false
consonants = "#{consonants}#{words[n][i]}"
i += 1
end
#removes consonants at beginning of word, moves them to the end of word, and adds 'ay.'
new_words << cut_and_paste(consonants, words[n])
end
end
new_words = new_words.join(" ")
return new_words
end
コードは、単一の単語の罰金に動作しますが、入力されたとき:
"速い茶色のキツネ"
はリターンが
"ethay ickquay brownay foxay" として戻ってきます
何らかの理由で、コードが最初の「複数子音」という単語を処理できますが、ループを通って戻るときに何かが間違っています。私はそれがfor-loopかwhile-loopの問題であるかどうかは分かりませんが、for-loopを使用しなかった前のバージョンで同じエラーが発生しているので、私は間違いありません。
私はループ内でiの値を設定しているので、新しい単語ごとに0にリセットされますが、そうでない理由は見当たりません。
私はこれまで同じ結果のループ.map
を使用しました。
それが助け場合は、失敗した具体的な例は次のとおりです。
it "translates many words" do
s = translate("the quick brown fox")
expect(s).to eq("ethay ickquay ownbray oxfay")
end
ここで私はテストの取得エラーです:ここについて話をするが、あなたは非常にそれを見つけることができます
#translate
translates a word beginning with a vowel
translates a word beginning with a consonant
translates a word beginning with two consonants
translates two words
translates a word beginning with three consonants
counts 'sch' as a single phoneme
counts 'qu' as a single phoneme
counts 'qu' as a consonant even when it's preceded by a consonant
translates many words (FAILED - 1)
Failures:
1) #translate translates many words
Failure/Error: expect(s).to eq("ethay ickquay ownbray oxfay")
expected: "ethay ickquay ownbray oxfay"
got: "ethay ickquay brownay foxay"
(compared using ==)
# ./04_pig_latin/pig_latin_spec.rb:65:in `block (2 levels) in <top (required)>'
Finished in 0.0193 seconds (files took 0.12399 seconds to load)
9 examples, 1 failure
Failed examples:
rspec ./04_pig_latin/pig_latin_spec.rb:63 # #translate translates many words
を'vowel?'と名付けられる)は 'vowels.include?(letter)'と同じくらい単純です。 –
'translate'メソッドで、whileループの構文が正しくありません。ここに作業コードを貼り付けることができますか? – Lavika
デイブ・ニュートン、情報ありがとう。私は約1ヶ月しかコーディングしていないので、私はどのくらい剃ることができないか分からないので、私は非常に明白な傾向があります。 –