diff --git a/lib/reverse_words.rb b/lib/reverse_words.rb index cb3cc8a..6f33a2e 100644 --- a/lib/reverse_words.rb +++ b/lib/reverse_words.rb @@ -1,4 +1,47 @@ +require 'pry' # A method to reverse each word in a sentence, in place. def reverse_words(my_words) - raise NotImplementedError + #split string into array of words + return my_words if my_words.nil? + + new_string = "" + var = "" + + my_words.length.times do |x| + if my_words[x] != " " + var += my_words[x] + else + new_string += string_reverse(var) + new_string += my_words[x] + var = "" + end + end + new_string += string_reverse(var) + + my_words.length.times do |x| + my_words[x] = new_string[x] + end + return my_words end + +def string_reverse(my_string) + return my_string if my_string.nil? + + return my_string if my_string.length <= 1 + + i = 0 + j = my_string.length - 1 + b = 0 + while i < j + b = my_string[i] + my_string[i] = my_string[j] + my_string[j] = b + i += 1 + j -= 1 + end + return my_string +end + +# test_string = "I like tomatoes" +# +# print reverse_words(test_string) diff --git a/specs/reverse_words_spec.rb b/specs/reverse_words_spec.rb index 2db8644..944b71d 100644 --- a/specs/reverse_words_spec.rb +++ b/specs/reverse_words_spec.rb @@ -1,6 +1,7 @@ require 'minitest/autorun' require 'minitest/reporters' require_relative '../lib/reverse_words' +require 'pry' describe "reverse words" do describe "basic tests" do @@ -16,7 +17,7 @@ test_string = "hello, world" reverse_words(test_string) - + # binding.pry test_string.must_equal ",olleh dlrow" end end