所以我一直在尝试用不同的示例来编写pig-latin方法。但是,最后的join方法只是简单地连接字符串的原始单词,而不是经过迭代的修改单词:
def translate(string)
alphabet = ("a".."z").to_a
vowels = %w{a e i o u}
consonant = alphabet - vowels
words = string.split
words.each do |word|
if vowels.include?(word[0])
word = word + "ay"
elsif word[0..2] == "sch"
word = word[3..-1] + word[0..2] + "ay"
elsif word[0..1] == "qu"
word = word[2..-1] + word[0..1] + "ay"
elsif word[1..2] == "qu"
word = word[3..-1] + word[0..2] + "ay"
elsif consonant.include?(word[0]) && consonant.include?(word[1]) && consonant.include?(word[2])
word = "#{word[3..-1]}#{word[0..2]}ay"
elsif consonant.include?(word[0]) && consonant.include?(word[1])
word = "#{word[2..-1]}#{word[0..1]}ay"
elsif consonant.include?(word[0])
word = "#{word[1..-1]}#{word[0]}ay"
end
end
p words.join(" ")
end
translate("apple pie")
translate("cherry")
translate("school")
translate("square")
translate("three")
translate("apple")
translate("cat")
这是它运行时给我的:
"apple pie"
"cherry"
"school"
"square"
"three"
"apple"
"cat"
2条答案
按热度按时间rmbxnbpk1#
使用正则表达式和case语句,可以将其压缩很多:
导致以下测试
true
:注意,我简化了第二个正则表达式,假设单词开头“qu”前面唯一的辅音是“s”(根据
/usr/share/dict/words
).8hhllhi22#
尝试使用map而不是each
像这样:
我建议阅读这个答案数组#each vs.array#map,因为它将阐明map和each之间的区别。您的每个块都返回原始单词数组,因此它从未更改。