forked from AdaGold/string-manipulation-practice
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathreverse_sentence.rb
52 lines (43 loc) · 1.11 KB
/
reverse_sentence.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# A method to reverse the words in a sentence, in place.
def reverse_sentence(my_sentence)
def reverse_sentence(sentence)
return nil if sentence.nil?
finish = nil
start = nil
on_first_word = true
is_finding_whitespace = sentence[-1] == ' '
(sentence.length - 1).downto(0) do |current_index|
current_char = sentence[current_index]
if is_finding_whitespace
if finish.nil? && current_char == ' '
finish = current_index
end
if start.nil? && sentence[current_index - 1] != ' '
start = current_index
end
else
# a word
if finish.nil? && current_char != ' '
finish = current_index
end
if start.nil? && sentence[current_index - 1] == ' '
start = current_index
end
end
if start.nil? && current_index == 0
start = current_index
end
if start && finish
if on_first_word
on_first_word = false
else
word = sentence.slice!(start..finish)
sentence << word
end
start = nil
finish = nil
is_finding_whitespace = !is_finding_whitespace
end
end
end
end