红宝石猪拉丁语翻译多个单词

时间:2013-01-13 22:38:15

标签: 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

2 个答案:

答案 0 :(得分: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(' ')

答案 1 :(得分: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