Ruby Pig拉丁语转换器
我目前正在做一个练习,其中包括将句子“快速棕色狐狸”转换为“Hetay-uickqay-rownbay-oxfay”Ruby Pig拉丁语转换器,ruby,Ruby,我目前正在做一个练习,其中包括将句子“快速棕色狐狸”转换为“Hetay-uickqay-rownbay-oxfay” def translate(sent) sent = sent.downcase vowels = ['a', 'e', 'i', 'o', 'u'] words = sent.split(' ') result = [] words.each_with_index do |word, i| translation = '' qu = fal
def translate(sent)
sent = sent.downcase
vowels = ['a', 'e', 'i', 'o', 'u']
words = sent.split(' ')
result = []
words.each_with_index do |word, i|
translation = ''
qu = false
if vowels.include? word[0]
translation = word + 'ay'
result.push(translation)
else
word = word.split('')
count = 0
word.each_with_index do |char, index|
if vowels.include? char
# handle words that start with 'qu'
if char == 'u' and translation[-1] == 'q'
qu = true
translation = words[i][count..words[i].length] + translation + 'ay'
result.push(translation)
next
end
break
else
# handle words with 'qu' in middle
if char == 'q' and translation[i-1] == 'u'
qu = true
translation = words[i][count +1..words[i].length] + 'ay'
result.push(translation)
next
else
translation += char
end
count += 1
end
end
# translation of consonant words without "qu"
if not qu
translation = words[i][count..words[i].length] + translation + 'ay'
result.push(translation)
end
end
end
result.join(' ')
end
puts translate("The quick brown fox")
然而,我得到的是“ethay uickqay ownbray oxfay”而不是“Hetay uickqay rownbay oxfay”
哪些方面需要纠正?我无法准确地指出问题所在。你能告诉我解决方法吗?这是一种非常程序化和复杂的方法。我不确定您检查
q
和u
的规则是什么,因为没有提到qu
作为特例:
一种简单得多的方法是将句子分成一组单词,并根据需要转换每个单词:
def translate(sent)
translation = sent.split(' ').map do |w|
vowels = %w(a e i o u)
word = w.downcase.split('')
if vowels.include? word[0]
"#{word}way"
else
"%s%say" % [word[1..-1], word[0]]
end
end
translation.join(' ').capitalize
end
puts translate("The quick brown fox")
# outputs Hetay uickqay rownbay oxfay
并且,对于1.9和可能的更高版本:
def translate(sent)
translation = sent.split(' ').map do |w|
vowels = %w(a e i o u)
word = w.downcase.split('')
if vowels.include? word[0]
"#{word.join}way"
else
"%s%say" % [word[1..-1].join, word[0]]
end
end
translation.join(' ').capitalize
end
puts translate("The quick brown fox")
显然,这两个都是例子,通过工作可能会做得更好。但它们说明了这一点
这利用了
map
和join
,并且可能可以进一步优化。此方法与您的方法之间的关键区别在于,您正在尝试以迭代方式构建翻译映射,而您可能不需要这样做。使用枚举函数,它们是使函数式编程风格更具表现力的一部分。学会思考“如何排列此数据集以获得所需的响应”,而不是“需要执行哪些步骤才能获得所需的响应”。您的代码很难推理。这样做的原因包括:一个长方法、嵌套的if表达式、变量的突变(word
在不同的时间点包含不同类型的数据)、错误的缩进。请考虑以下操作:将所有有意义的任务分成不同的方法,不要不必要地改变变量的内容,听起来像一个家庭作业。[ H ],“E”] Tay[ [ U ],“I”,“C”,“K”] QA[ [ R ],“O”,“W”,“N”]湾[“O”,“X”] Fay。这是您的代码在命令提示符下生成的内容@mcfinnigan@iJava我明白了,ruby 1.8和1.9之间的区别。等一下,非常感谢你的帮助。