Reverse a string in Ruby

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

    Here's one way to do it with inject and unshift:

    "Hello world".chars.inject([]) { |s, c| s.unshift(c) }.join
    

提交回复
热议问题