【发布时间】:2015-03-17 02:01:34
【问题描述】:
我正在尝试编写一个程序,将带有一些大写单词和标点符号的字符串翻译成 Pig Latin。条件如下:
1) 以元音开头的单词应该只加上“ay”。
2) 以“sch”或“qu”或“squ”或“ch”等单个音素开头的单词应将所有这些字符移动到末尾,而不仅仅是第一个字母,然后加上“ay” .
3) 以一个辅音开头的单词的常规猪拉丁语规则(即“Well”,=> 'Ellway,,)。
4) 应保留大小写和标点符号,但如果字母不以元音开头,则首字母会发生变化。所以“Well”会变成“Ellway”。
一切正常,除了我的字符串的第一个单词。字符串的第一个单词永远不会满足第四个条件。因此,例如,“Well”变成了“ellWay”。所以标点符号有效,但大写字母不能正常工作。
编辑:我意识到只有当单词不以元音开头时才会出现此问题。因此,“Actually”变成了“Actuallyay”(应该如此),但“Quaint”变成了“aintQuay”,而它应该是“Aintquay”。所以,这里是我实际将猪拉丁语传递到名为 pig_latin 的数组的代码:
string = string.split(' ')
pig_latin = []
string.each do |word|
if vowels.include?(word[0])
pig_latin << word + "ay"
elsif (consonants.include?(word[0]) && consonants.include?(word[1]) && consonants.include?(word[2])) || word[1..2].include?('qu')
pig_latin << (word[3..-1] + word[0..2] + "ay")
elsif (consonants.include?(word[0]) && consonants.include?(word[1])) || word[0..1].include?('qu')
pig_latin << (word[2..-1] + word[0..1] + "ay")
else
pig_latin << (word[1..-1] + word[0] + "ay")
end
end
这是我处理大写和标点符号的代码部分。澄清一下, pig_latin 是传入了猪拉丁化短语的数组。 uppercase_alphabet 是我创建的包含所有大写字母的数组:
idx1 = 0
while idx1 < pig_latin.count
word = pig_latin[idx1]
idx2 = 0
while idx2 < word.length
if uppercase_alphabet.include?(word[idx2])
word[idx2] = word[idx2].downcase
word[0] = word[0].upcase
end
if punctuation.include?(word[idx2])
word[word.length], word[idx2] = word[idx2], ''
end
idx2 += 1
end
idx1 += 1
end
pig_latin.join(' ')
编辑:这是概述我正在使用的各种数组的代码:
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
lowercase_alphabet = ('a'..'z').to_a
uppercase_alphabet = ('A'..'Z').to_a
alphabet = lowercase_alphabet + uppercase_alphabet
punctuation = ['.', ',', ';', '?', '!', ':']
consonants = []
alphabet.each do |letter|
consonants << letter unless vowels.include?(letter)
end
而且,这是我在使用以下字符串运行测试时遇到的错误:“嗯,我有,甚至没有。看过那部电影。” (我明白标点符号没有意义)。
1) #translate retains punctuation from the original phrase
Failure/Error: s.should == "Ellway, Iay avehay, otnay evenay. eensay atthay oviemay."
expected: "Ellway, Iay avehay, otnay evenay. eensay atthay oviemay."
got: "ellWay, Iay avehay, otnay evenay. eensay atthay oviemay." (using ==)
# ./spec/04_pig_latin_spec.rb:83:in `block (2 levels) in <top (required)>
【问题讨论】:
标签: ruby capitalization punctuation