Reverse a string in Ruby

前端 未结 22 1042
广开言路
广开言路 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 06:59

    Use

    def reverse_string(string) # Method reverse_string with parameter 'string'.
      loop = string.length # int loop is equal to the string's length.
      word = '' # This is what we will use to output the reversed word.
      while loop > 0 # while loop is greater than 0, subtract loop by 1 and add the string's index of loop to 'word'.
        loop -= 1 # Subtract 1 from loop.
        word += string[loop] # Add the index with the int loop to word.
      end # End while loop.
      return word # Return the reversed word.
    end # End the method.
    
    0 讨论(0)
  • 2020-12-05 07:01
    string = "This is my string"
    string_arr = string.split('')
    n = string_arr.length
    new_arr = Array.new
    
    17.times do |i|
      new_arr << string_arr.values_at(n - i)
    end
    
    reversed_string = new_arr.flatten.join('')
    => "gnirts ym si sihT"
    
    0 讨论(0)
  • 2020-12-05 07:03

    There's already an inplace reverse method, called "reverse!":

    $ a = "abc"
    $ a.reverse!
    $ puts a
    cba
    

    If you want to do this manually try this (but it will probably not be multibyte-safe, eg UTF-8), and it will be slower:

    class String
      def reverse_inplace!
        half_length = self.length / 2
        half_length.times {|i| self[i], self[-i-1] = self[-i-1], self[i] }
        self
      end
    end
    

    This swaps every byte from the beginning with every byte from the end until both indexes meet at the center:

    $ a = "abcd"
    $ a.reverse_inplace!
    $ puts a
    dcba
    
    0 讨论(0)
  • 2020-12-05 07:03

    Consider looking at how Rubinius implements the method - they implement much of the core library in Ruby itself, and I wouldn't be surprised if String#reverse and String#reverse! is implemented in Ruby.

    0 讨论(0)
  • 2020-12-05 07:04

    This is the solution that made the most sense to me as a ruby beginner

    def reverse(string)
      reversed_string = ''
    
      i = 0
      while i < string.length
        reversed_string = string[i] + reversed_string
        i += 1
      end
    
      reversed_string
    end
    
    p reverse("helter skelter")
    
    0 讨论(0)
  • 2020-12-05 07:06

    Hard to read one-liner,

    def reverse(a)
        (0...(a.length/2)).each {|i| a[i], a[a.length-i-1]=a[a.length-i-1], a[i]}
        return a
    end
    
    0 讨论(0)
提交回复
热议问题