Reverse a string in Ruby

前端 未结 22 1109
广开言路
广开言路 2020-12-05 06:36

How do you reverse a string in Ruby? I know about string#reverse. I\'m interested in understanding how to write it in pure Ruby, preferably an in-place solution.

22条回答
  •  不知归路
    2020-12-05 07:16

    def reverse(string)
      result = ""
      idx = string.length - 1
      while idx >= 0
      result << string [idx]
      idx = idx - 1
     end
    
     result
    
    end 
    

提交回复
热议问题