我正在开发一项Ruby任务,负责建立一个小型的,测试驱动的程序,将一些单词和短语翻译成猪拉丁语。
首先,让我发布我到目前为止的代码。
#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
答案 0 :(得分:1)
在这里谈论很多,但如果你能把事情分解成更小的部分,你会发现更容易遵循自己的逻辑。
translate
方法应该将一系列单词翻译成pig Latin。每个单词都可以独立处理,所以让我们从这开始吧。让我们写translate
来获取一个短语,将其分解为单词,将每个单词发送到另一个要翻译的方法,然后将结果加入到翻译的字符串中:
def translate(input)
input.split.map { |word| translate_word(word) }.join(' ')
end
这就是整个方法!这里真正的力量在于Enumerable#map
方法。这将获取任何数组,将每个元素传递给提供的块,并返回一个包含结果元素的新数组。
现在你只需要编写translate_word
方法,它将唯一的参数作为一个未翻译的单词,并将返回一个翻译的单词:
def translate_word(word)
...single-word translation logic here...
end