Reverse String in Ruby – Multiple ways !

Hello again!

I am continuing answering to your questions, this one came from marthab86_.

marthab86_ asks:

“I know Ruby has .reverse! , but can you show me how to actually reverse a word or a sentence without reverse ?”

I am sure that there are many resources that have solution for this problem, but since I am asked, lets have one more example here 🙂

So today’s question is:

How to reverse string in Ruby ?

 

Here is what we are going to do. We are going to algorithmically and via the code answer to the following questions in Ruby:
a. How to reverse a string  ?
b. How to reverse each word in a sentence?
c. How to reverse word order in a sentence?
Ok, let’s start.

a. How to reverse a string ?

Since I didn’t have any instructions about complexity, I will do it  the easiest way.

a. Get a number of characters of the string we want to reverse
b. Loop that loops through each characters of the string from last to first
d. Have a new string that append characters, one at a time from, the old string to the new string

If we put it in a code, it will look like this:
Note: I am using Ruby, but this will be almost the same in any other language

def reverse_whole_string(string)
	raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
	end_loop = string.length
	new_string = ''
	while end_loop >= 0
		end_loop -= 1 # arrays start with 0, so we need to do end_loop -1 first
		new_string += string[end_loop]
	end
	new_string
end

The only addition I have here is that I have raised StandardError if a String is nil or an empty string, otherwise it is exactly the same as an algorithm above.

b. How to reverse each word in a sentence?

This one is a bit more complex, but the idea is the same:
a.  For easier manipulation transform sentence into an array of words by splitting string by space
b. Loop through each word in a sentence
c. Reverse each word in a sentence the same way we reverse the string in the example above
d. Add reversed word to a new array
e. Convert new array of reversed words into String by joining elements by space

Here is the code:

def reverse_each_word_in_a_string(string)
	raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
	words = string.split(" ") #splitting string into an Array of words
	new_sentence = []
	words.each do |word|
		# doing the same thing as reverse_whole_string
		# but with eah word from an array
		end_loop = word.length
		new_string = ''
		while end_loop > 0
			end_loop -= 1
			new_string += word[end_loop] #Reversing every letter of each word
		end
		new_sentence << new_string # appending every word to an new Array
		# or you could just do this: new_sentence << reverse_whole_string(word)
	end
	new_sentence.join(' ') #joining Array into a string delimited by spaces
end

This is it, not so bad right ?

So the last thing is:

c. How to reverse word order in a sentence?

a. Convert sentence into an array of words by splitting string by space
b. Loop through each  word starting from last
c. Add every element of an array in a reverse order to a new array
d. Convert array into string by joining array by space

def reverse_word_order_in_a_sentence(string)
	raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
	words = string.split(" ")
	new_sentence = []
	end_loop = words.length
	while end_loop > 0
		end_loop -= 1
		new_sentence << words[end_loop]
	end
	new_sentence.join(' ')
end

This is it, if you have any questions or concerns please leave them in the comment section.

Source code  is available here .

In the second part we will talk about, why built-in ruby functions  are better, and how to measure runtime of your application.

Stay tuned,

Anatoly

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. […] ← How to reverse a String not using built-in reverse method ? How to reverse every word in a se… […]

  2. natreffi

    in your first example since youre decrementing end_loop after the comparison you’re winding up with an additional final character at -1 where

    new_string += string[-1] #=> winds up with a trailing “g”

    perhaps a more concise way to do this would be to use the downto method:

    def reverse_whole_string(string)
    raise StandardError.new(‘Passed string cant be empty’) if string.nil? || string.empty?
    new_string = ””
    for i in (string.length – 1).downto(0)
    new_string += string[i]
    end
    new_string
    end

    1. Anatoly Spektor

      Thank you Natreffi for good example!

arrow