我正在研究The Odin Project中的pig_latin_spec示例,并且在处理特殊情况时遇到一些困难,其中一个单词包含“qu”,并且这些字符需要被视为一个音素。例如“quiet”=> “ietquay”和“square”=> “aresquay”。
以下是违规if
声明:
if word.include? "qu"
start_index = word.index("q")
prefix = word[0..(start_index+1)] + "ay"
pig_word = word[(start_index+2)..-1] + prefix
end
这会产生“ietquay”而不是“isququay”。相反,我得到“uaresqay”。我在俯瞰什么?
以下是整个计划:
def translate(input)
all_words = []
pig_word = ""
input.split.map do |word, i|
if 'aeiou'.include? word[0]
pig_word = word + "ay"
else
prefix = word[0] + "ay"
pig_word = word[1..-1] + prefix
if word.include? "qu"
start_index = word.index("q")
prefix = word[0..(start_index+1)] + "ay"
pig_word = word[(start_index+2)..-1] + prefix
end
unless 'aeiou'.include? word[1]
prefix = word[0..1] + "ay"
pig_word = word[2..-1] + prefix
unless 'aeiou'.include? word[2]
prefix = word[0..2] + "ay"
pig_word = word[3..-1] + prefix
end
end
end
all_words << pig_word
end
"#{[all_words].join(" ")}"
end
答案 0 :(得分:1)
正在运行“qu”的特殊外壳,但后来用unless
中的逻辑替换了这个条件:
'aeiou'.include? word[1]
因为false
的条件为word = "square"
(因为“q”不在“aeiou”中)。
快速修补/修复是使用if...elsif
使两个竞争条件块互斥,当单词包含“qu”时,它将不会进一步检查。
if word.include? "qu"
start_index = word.index("q")
prefix = word[0..(start_index+1)] + "ay"
pig_word = word[(start_index+2)..-1] + prefix
elsif ! 'aeiou'.include? word[1]
prefix = word[0..1] + "ay"
pig_word = word[2..-1] + prefix
unless 'aeiou'.include? word[2]
prefix = word[0..2] + "ay"
pig_word = word[3..-1] + prefix
end
end
请注意,这可能无法带来完美的翻译,它只会解决您在此处提出的问题。
答案 1 :(得分:-1)
实现Neil的建议编辑,这是完整功能的代码:
def translate(input)
all_words = []
pig_word = ""
input.split.map do |word, i|
first_vowel = word.index(/[aeiou]/) #dat first vowel occurence
if first_vowel == 0 #words that begin with a vowel
pig_word = word + "ay"
elsif word.include? "qu" #words that don't begin with a vowel but include "qu".
first_vowel = word.index(/[aeio]/) #first vowel not counting "u"
start_index = word.index("q")
prefix = word[0..(first_vowel-1)] + "ay"
pig_word = word[first_vowel..-1] + prefix
end
if first_vowel >= 1 #words that don't begin with vowels or have "qu"
prefix = word[0..first_vowel-1] + "ay"
pig_word = word[first_vowel..-1] + prefix
end
all_words << pig_word
end
"#{[all_words].join(" ")}"
end