您可以根据if语句条件附加到数组中的特定元素吗?

我是一名开发人员训练营学生,我的一个项目遇到了问题。 我们使用Ruby来编写Pig Latin页面。 我得到它通过测试,直到它需要接受多个单词:

def pig_latina(word) # univeral variables vowels = ['a','e','i','o','u'] user_output = "" # adds 'way' if the word starts with a vowel if vowels.include?(word[0]) user_output = word + 'way' # moves the first consonants at the beginning of a word before a vowel to the end else word.split("").each_with_index do |letter, index| if vowels.include?(letter) user_output = word[index..-1] + word[0..index-1] + 'ay' break end end end # takes words that start with 'qu' and moves it to the back of the bus and adds 'ay' if word[0,2] == 'qu' user_output = word[2..-1] + 'quay' end # takes words that contain 'qu' and moves it to the back of the bus and adds 'ay' if word[1,2] == 'qu' user_output = word[3..-1] + word[0] + 'quay' end # prints result user_output end 

我不知道怎么做。 这不是家庭作业或任何事情。 我试过了

  words = phrase.split(" ") words.each do |word| if vowels.include?(word[0]) word + 'way' 

但我认为else声明搞砸了所有这一切。 任何见解将不胜感激! 谢谢!!

 def pig_latina(word) prefix = word[0, %w(aeiou).map{|vowel| "#{word}aeiou".index(vowel)}.min] prefix = 'qu' if word[0, 2] == 'qu' prefix.length == 0 ? "#{word}way" : "#{word[prefix.length..-1]}#{prefix}ay" end phrase = "The dog jumped over the quail" translated = phrase.scan(/\w+/).map{|word| pig_latina(word)}.join(" ").capitalize puts translated # => "Ethay ogday umpedjay overway ethay ailquay" 

我会将你的逻辑分成两种不同的方法,一种是转换单个单词的方法(有点像你有的),另一种方法是取一个句子,分割单词,然后在每个单词上调用你以前的方法。 它可能看起来像这样:

 def pig(words) phrase = words.split(" ") phrase.map{|word| pig_latina(word)}.join(" ") end