2016-04-03 71 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