我正在研究一個Ruby任務,它負責構建一個小型的,測試驅動的程序,它可以將一些單詞和短語翻譯成拉丁語。for循環或while循環在第三次和第四次迭代中不起作用
首先,讓我發佈我到目前爲止的代碼。
#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循環或while循環的問題,但由於我在之前的版本中沒有使用for循環時出現相同的錯誤,我懷疑這是一次。
因爲我在循環內設置了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
無關,但在'is_vowel'是有條件的(應被命名爲「元音?」)就像'vowels.include?(letter)'一樣簡單,就這麼簡單。 –
在你的'translate'方法中,while循環的語法不正確。你能在這裏粘貼工作代碼嗎? – Lavika
戴夫牛頓,感謝您的信息。我只有一個月左右的編碼,所以我傾向於非常明確,因爲我不知道我能削減多少。 –