junky
junky

Reputation: 1478

Ruby method to reverse characters not recursing for words

The 'reverse by characters' works but the third test "by words" doesn't -

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

Upvotes: 1

Views: 179

Answers (1)

verdesmarald
verdesmarald

Reputation: 11866

The problem is in this loop:

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

The else block reverses the current word and adds it to the output string, but it only runs when the loop encounters a space character. Since there is no space at the very end of the string, the last word is never added to the output. You can fix this by adding new_string+= reverse_itti(word, 'by_character') after the end of the loop.

Also, you probably want to add a space to the end of the output string in the else block, too.

Upvotes: 2

Related Questions