Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to reverse a string in Ruby

okwudili onyejiaku

Overview

In Ruby, we can use the reverse method to reverse a string. The reverse method reverses the characters of a string and returns a new string with the characters of the original string in reverse order.

Syntax

str.reverse

Parameters

  • str: The string we want to reverse.

Return value

The reverse method returns a new string with the reversed characters of string str.

Example

# create some strings
str1 = "Edpresso"
str2 = "is"
str3 = "awesome!"

# reverse the strings
a = str1.reverse
b = str2.reverse
c = str3.reverse

# print results
puts a 
puts b
puts c
Reverse a String in Ruby using reverse method

Explanation

  • Lines 2 to 4: We create strings and initialize them with values.
  • Lines 7 to 9: We call the reverse method on the strings that we created.
  • Lines 12 to 14: We print the results to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring