Reverse a string in Ruby

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

    Here's an alternative using the xor bitwise operations:

    class String
    
      def xor_reverse
        len = self.length - 1
        count = 0
    
        while (count < len)
          self[count] ^= self[len]
          self[len] ^= self[count]
          self[count] ^= self[len]
    
          count += 1
          len -= 1
        end
    
      self
    end
    
    "foobar".xor_reverse
    => raboof
    

提交回复
热议问题