-1

我需要编写一个将普通语音转换为猪拉丁语的程序。我写

def translate(*string)
  word = []
  word_string = []
  s = []
  i = 0
  a = nil


  #enters input from user into individual arrays spots
  #removes spaces
  string[0].scan(/\w+/).each { |x| word << x }

  #goes through each word and does operation
  while i < word.count
     word[i].scan(/./) { |x| word_string << x }

     #checks if starts with vowel
     if word_string[0].include?("aeiou" || "AEIOU")
       word_string = word_string << "ay"
       s[i] << word_string.join('')

     #checks if starts with Qu or qu  
     elsif word_string[0] + word_string[1] == "qu" || word_string[0] + word_string[1] == "Qu"
       word_string.delete_at(0) && word_string.delete_at(1)
       word_string << "quay"
       s[i] = word_string.join('')

     #checks if starts with 3 consonants   
     unless (word_string[0] + word_string[1] + word_string[2]).include?("aeiou") 
       a = word_string[0] + word_string[1] + word_string[2]
       word_string.delete_at(0) && word_string.delete_at(1) && word_string.delete_at(2)
       word_string << (a + "ay")
       s[i] = word_string.join('')
       a = nil

    #checks if starts with 2 consonants   
    unless (word_string[0] + word_string[1]).include?("aeiou")
       a = word_string[0] + word_string[1]
       word_string.delete_at(0) && word_string.delete_at(1)
       word_string << (a + "ay")
       s[i] = word_string.join('')
       a = nil

   #check if starts with 1 consonants
   else
      a = word_string[0]
      word_string.delete_at(0)
      word_string << (a + "ay")
      s[i] = word_string.join('')
      a = nil
   end

  i += 1

  end
s.join(" ")
end

它返回给我一个错误说

pig_latin.rb:58: syntax error, unexpected $end, expecting kEND

我查看了错误,这意味着我在某个地方错过了一个结尾,或者我有一个太多,但我找不到它。我有一个 def 结束,一个 while 结束和一个 if 结束,所以问题不存在。我认为它可能在最初的几个链接中的某个地方,我在其中编写了扫描文件以对文本进行排序,但它似乎也不在那里。我需要另一双眼睛看看,我找不到。另外,如果有更好的方法来写这个,请告诉我。

4

1 回答 1

1

这更像是代码应该看起来的样子,如果它是用更多的 Ruby 方式编写的:

def translate(string)

  pig_latin = []

  words = string.split(/\W+/)

  words.each do |word|

    case word
    when /^[aeiou]/i
      pig_latin << (word + "ay")

    when /^qu/i
      word << word[0,2] << 'ay'
      pig_latin << word[2 .. -1]

    when /^[^aeiou]{3}/i
      word << word[0,3] << 'ay'
      pig_latin << word[3..-1]

    when /^[^aeiou]{2}/i
      word << word[0, 2] << 'ay'
      pig_latin << word[2 .. -1]

    else
      word << word[0] << 'ay'
      pig_latin << word[1 .. -1]
    end

  end
  pig_latin.join(' ')
end

puts translate('the rain in spain stays mainly on the plain')
=> ethay ainray inay ainspay aysstay ainlymay onay ethay ainplay

我会以不同的方式检查辅音。

它的工作原理留给读者去弄清楚。如果这是一项家庭作业,请花时间弄清楚它是如何工作的,因为知道它的作用很重要。抄袭别人的作品……嗯,现在网上有,大家都可以搜索找到,不要抄袭。

于 2013-04-22T07:03:45.890 回答