Ruby方法来反转字符而不是递归字

时间:2012-05-04 01:32:26

标签: 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

1 个答案:

答案 0 :(得分: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块中的输出字符串末尾添加一个空格。