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

问题出在这个循环中:

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

最新更新