意外的结束kend ruby​​ piglatin计划

时间:2013-04-22 02:26:37

标签: ruby

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

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 end,while end和if end,所以问题不在那里。我认为它可能是在前几个链接中的某个地方,我在那里编写扫描来对文本进行排序,但它看起来也不像它。我需要另外一双眼睛来看看,我找不到它。如果有更好的方式来写这个,请告诉我。

1 个答案:

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

我已经用不同的方式检查了辅音。

它如何运作留给读者弄清楚。如果这是一个家庭作业,花点时间弄清楚它是如何工作的,因为知道它的作用很重要。复制其他人的工作......好吧,这是现在的互联网,所以任何人都可以搜索并找到它,所以不要抄袭。