2016-04-03 84 views
0

我試圖遍歷元音"aeiou"並將每個字母向前移動,返回字符串"eioua"。這是我的代碼:Ruby通過字符串迭代

def vowel(letter) 
    vowels = "aeiou" 
    string = "" 
    index = 0 
    while index < letter.length 
    current_id = vowels.index(letter) 
    next_vowel = vowels[current_id + 1] 
    string += next_vowel 
    index += 1 
    end 
    string 
end 

當我通過"aeiou"作爲參數傳遞給我的方法,它只是需要"a",並打印"eeeee"

vowel("aeiou") # => "eeeee" 
+0

你的問題是什麼? – sawa

回答

2

你總是追加元音,通過索引current_id = vowels.index(letter)發現(加一。)這就是爲什麼代碼附加e(旁邊a)的五倍。 index變量僅用作循環計數器。

這個代碼還有一個小故障:當letter是最後一個,current_id是最後一個字母的索引,vowels[current_id + 1]nil

目前我無法爲此問題提供解決方案,因爲說明和預期結果不一致:「將每個字母向前移動」在給定輸入上不會生成"eioua"

+0

啊,對不起,我不是指一封信 - 我的意思是每個元音都會成爲它右邊的下一個元音,所以「a」會變成「e」,「u」變成「a」。我也注意到元音[current_id + 1]變成零,但我仍然不完全明白你爲什麼要詳細說明?感謝您的有用反饋! –

+1

當'current_id'是最後一個字母的索引時,'current_id + 1'是一個大於字符串長度的索引,也就是說,它是一個不存在的索引。 ''abc'[3]'例如'nil'。 – mudasobwa

1

如果你想旋轉單詞的字母(並形成一個新的單詞,而不是在地方修改字)的一個方法是:

str = "aeiou" 

new_str = str.chars.rotate.join. #=> "eioua" 
str        #=> "aeiou" 

如果要修改的地方串:

str.object_id.      #=> 70128532752540 
str.replace(str.chars.rotate.join) #=> "eioua" 
str        #=> "eioua" 
str.object_id      #=> 70128532752540 
+1

這是一個更好的方法。 Ruby具有所有這些基於枚舉方法的簡短方法,它們可以結合使用時非常棒。 – tadman