2013-08-28 38 views
0

我是一个开发者训练营的学生,在和我的一个项目的问题。我们使用Ruby来编写猪拉丁文页面。我得到它通过测试,直到它需要接受多个单词的点:可以追加基于if语句条件数组中的特定元素?

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声明搞得一团糟。任何有识之士将不胜感激!谢谢!!

+2

你的代码是非常复杂的理解。而是告诉我们你想要的样本串和预期输出.. –

+1

什么是你的问题?我在底部代码部分没有看到else语句。 – squiguy

+1

你的代码混合了一些东西。您的总体分裂短语,单词,将每个单词,然后再结合的逻辑,正确的是(你可以用'phrase.split(“‘){.collect | W | pig_latina(W)}。加入(’”)' )。但是,处理这个词的详细代码几乎试图处理短语,但不完全。您可能需要在每个“qu”个案之前都有一个“else”,因为它们与前两种情况相互排斥。其余的看起来有点凌乱,但我认为是健全的。 – lurker

回答

1
def pig_latina(word) 
    prefix = word[0, %w(a e i o u).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" 
+0

感谢修正,PJS :) – tigeravatar

+0

谢谢!这有助于对事物进行透视。 –

1

我想你的逻辑分离成两种不同的方法,转换一个字(有点像你)一个方法,并采取了一句,分裂的话,并在调用前一种方法对每个人的另一种方法。这可能是这样的:

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