2012-05-04 23 views
1

的作品,但第三次測試「者言」「通過人物倒」不 -Ruby的方法來扭轉字符不是遞歸的話

expected: "sti gniniar" 
    got: "sti" (using ==) 

def reverse_itti(msg, style='by_character') 

    new_string = '' 
    word = '' 

    if style == 'by_character' 
    msg.each_char do |one_char| 
     new_string = one_char + new_string 
    end 
    elsif style == 'by_word' 
    msg.each_char do |one_char| 
     if one_char != ' ' 
     word+= one_char 
     else 
     new_string+= reverse_itti(word, 'by_character') 
     word='' 
     end 
    end 
    else 
    msg 
    end 
    new_string 
end 

describe "It should reverse sentences, letter by letter" do 

    it "reverses one word, e.g. 'rain' to 'niar'" do 
    reverse_itti('rain', 'by_character').should == 'niar' 
    end 
    it "reverses a sentence, e.g. 'its raining' to 'gniniar sti'" do 
    reverse_itti('its raining', 'by_character').should == 'gniniar sti' 
    end 
    it "reverses a sentence one word at a time, e.g. 'its raining' to 'sti gniniar'" do 
    reverse_itti('its raining', 'by_word').should == 'sti gniniar' 
    end 

end 

回答

2

的問題是在這個循環:

msg.each_char do |one_char| 
    if one_char != ' ' 
    word+= one_char 
    else 
    new_string+= reverse_itti(word, 'by_character') 
    word='' 
    end 
end 

else塊反轉當前單詞並將其添加到輸出字符串,但它只在循環遇到空格字符時才運行。由於在字符串的最後沒有空格,因此最後一個單詞不會被添加到輸出中。您可以通過在循環結束後添加new_string+= reverse_itti(word, 'by_character')來解決此問題。

另外,您可能還想在else塊的輸出字符串的末尾添加一個空格。