3

我正在努力用 ruby​​ 创建一个猪拉丁语翻译器。它适用于大多数单词,但我在一次使用多个单词时遇到了一些麻烦。例如,当您输入单词“apple”时,您会得到“appleay”,但如果输入了多个单词,则不会翻译它们。我一直在寻找解决方案,但一无所获。这里的其他一些线程对让我走到这一步非常有帮助。任何提示将非常感谢。

我还在 if/else 语句中添加了几个例外,以允许正确翻译“quiet”和“square”,其中“qu”被认为是辅音。

在此先感谢您的帮助!

def translate (word)
  alpha = ('a'..'z').to_a
  vowels = %w[a e i o u]
  consonants = alpha - vowels

  if vowels.include?(word[0..0])
    word + 'ay'
  elsif consonants.include?(word[0..0]) && consonants.include?(word[1..1])
    word[2..-1] + word[0..1] + 'ay'
  elsif word[0..1] == "qu" 
    word[2..word.length]+"quay"
  elsif word[0..2] == "squ"
     word[3..word.length]+"squay"
  else consonants.include?(word[0])
    word[1..-1] + word[0..0] + 'ay'
  end

end
4

2 回答 2

1

你可以这样做:

Alpha = ('a'..'z').to_a
Vowels = %w[a e i o u]
Consonants = Alpha - Vowels

def translate(word)
  if Vowels.include?(word[0])
    word + 'ay'
  elsif Consonants.include?(word[0]) && 
    Consonants.include?(word[1])
    word[2..-1] + word[0..1] + 'ay'
  elsif word[0..1] == "qu" 
    word[2..-1]+"quay"
  elsif word[0..2] == "squ"
     word[3..-1]+"squay"
  else Consonants.include?(word[0])
    word[1..-1] + word[0..0] + 'ay'
  end
end

puts "Enter some text to translate"
text = fgets
puts text.split.map(&method(:translate)).join(' ')
于 2013-01-13T22:41:02.387 回答
0

把它分解成多种方法怎么样?即,一种将字符串分解为单词的方法,然后将这些单词发送到另一种方法进行翻译,然后再将它们连接在一起并给出输出。

def translator(sentence)
  words_to_translate = sentence.split(" ")
  translated_words = words_to_translate.map {|word| translate_word(word)}
  translated_sentence = translated_words.join(" ")
end

def translate_word(word)
  ...code here
  return a word
end
于 2014-01-07T15:21:02.557 回答