Reverse a string in Ruby

前端 未结 22 1043
广开言路
广开言路 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
    
    0 讨论(0)
  • 2020-12-05 07:09
    "abcde".chars.reduce{|s,c| c + s }          # => "edcba"
    
    0 讨论(0)
  • 2020-12-05 07:09

    A simple classic way with n/2 complexity

    str = "Hello World!";
    puts str;
    
    for i in 0..(str.length/2).to_i
      mid = (str.length-1-i);
      temp = str[i];
      str[i] = str[aa];
      str[aa] = temp;
    end
    
    puts str;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-05 07:14
    def palindrome(string)
    
      s = string.gsub(/\W+/,'').downcase
    
      t = s.chars.inject([]){|a,b| a.unshift(b)}.join
    
      return true if(s == t)
    
      false
    
    end
    
    0 讨论(0)
提交回复
热议问题