1

“按字符反转”有效,但第三次测试“按单词”不起作用 -

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
4

1 回答 1

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 块的输出字符串末尾添加一个空格。

于 2012-05-04T01:42:29.200 回答