How to reverse a string in ruby

github logo ・1 min read

You can do this:

 def my_reverse(str)
  str.chars.inject {|a, b| b + a}
 end


 > my_reverse("idol")
 => "lodi"

You can also monkey patch the String object:

 class String
   def my_reverse
     self.chars.inject {|a, b| b + a}
   end
 end

 > "idol".my_reverse
 => "lodi"

and will print the same result :)

Warning: Be extra careful on monkey patching ruby objects.

twitter logo DISCUSS
Classic DEV Post from Jun 24

How do you handle unproductive days at work?

help to boost productivity and motivation

Maynard Cabalitan profile image
Ruby on rails dev

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️