Reverse a string in Ruby

前端 未结 22 1085
广开言路
广开言路 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:13

    def reverse(string)
    reversed_string = ""
    
    idx = 0
    while idx < string.length
    reversed_string = string[idx] + reversed_string
    idx += 1
    end
    
    return reversed_string
    end
    

提交回复
热议问题