Ruby program to reverse a string

Reversing a string

We can print the reverse a given number by below ways

By .reverse predefined method

puts "Enter the String:"
str1=gets.chomp

puts "The reverse of #{str1} is #{str1.reverse}" 

 

Output

Enter the String:
 ruby
The reverse of ruby is ybur

 

By loop

puts "Enter the String:"
str1=gets.chomp

newstr= ' '

for  i in  1..str1.length
    newstr+=str1[str1.length - i]
end

puts "The reverse of #{str1} is #{newstr}"

 

 

Output

Enter the String:
 ruby
The reverse of ruby is ybur