“按字符反转”有效,但第三次测试“按单词”不起作用 -
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