2015-09-17 50 views
-2

我试图输入一个字符串,并输出相同的字符串与每个字母在字母表中的一个字母。所以“嗨”会变成“ij”。这是迄今为止的代码,我不知道为什么它不起作用。它只是跳直“这不是字母表中的一个字母”
这里是我的代码:
我使用Ruby中的正确循环

def LetterChanges(str) 

    count = 0 

x = str.split(//).each do |com| 

    my_array = ('a'..'z').to_a 

    if my_array.include? com 
     if my_array[count] != com 
     count += 1 
     else 
     puts my_array[count + 1] 
     end 

    else 
     puts "this is not a letter of the alphabet" 
    end 

    end 

end 

LetterChanges("hello world") 

回答

0

,你怎么看待这种方法吗?

def LetterChanges(str) 
    str.split(//).each { |i| i.next! if (('a'..'z').include? i) }.join() 
end 
+0

哈哈哇哇我大量复杂这没有我。我确实尝试过类似的东西,但.next根本不适用于我,我没有意识到使用感叹号改变了它。你能解释我为什么不工作吗? – Rebs

+0

@RebekahParsons在这个块的逻辑问题:'if my_array [count]!= com count + = 1 else puts my_array [count + 1] end' –