Ruby Algorithm Series #2: Reverse a String Problem in Ruby A Complete Guide with Validation and TDD/BDD Testing

Algorithm to Reverse a String

Problem Statement

Write a program to reverse a given string without using any built-in reverse methods or functions. The program should take a string as input and output the string in reverse order.

Approach

  1. Input Validation:
    • Ensure the input is a valid string.
  2. Iterative Method:
    • Use a loop to iterate over the string from the end to the beginning.
    • Append each character to a new string.
  3. Alternative Methods:
    • Use two-pointer technique to swap characters in place (if working with mutable data structures, such as arrays).
  4. Output:
    • Return or print the reversed string.

Steps

  1. Initialize an empty string (reversed).
  2. Traverse the original string from the last character to the first using a decrementing loop.
  3. Append each character to the reversed string.
  4. Return the reversed string.
class StringReverser
    # Method to reverse a string
    def self.reverse_string(input)
      validate_input(input) # Validate the input
      reversed = ""         # Initialize an empty string for the reversed result
  
      # Iterate over the string from the end to the beginning
      (input.length - 1).downto(0) do |index|
        reversed += input[index]
      end
  
      reversed
    end
  
    private
  
    # Input validation to ensure the input is a string
    def self.validate_input(input)
      unless input.is_a?(String)
        raise ArgumentError, "Input must be a valid string."
      end
    end
  end
  
  # Example Usage
  if __FILE__ == $0
    input_string = "hello"
    puts "Original String: #{input_string}"
    puts "Reversed String: #{StringReverser.reverse_string(input_string)}"
  
    # Test Cases
    require 'rspec/autorun'
  
    RSpec.describe StringReverser do
      describe '.reverse_string' do
        context 'when input is a valid string' do
          it 'reverses a normal string' do
            expect(StringReverser.reverse_string("hello")).to eq("olleh")
          end
  
          it 'returns an empty string when input is empty' do
            expect(StringReverser.reverse_string("")).to eq("")
          end
  
          it 'reverses a single-character string' do
            expect(StringReverser.reverse_string("a")).to eq("a")
          end
  
          it 'reverses a string with spaces' do
            expect(StringReverser.reverse_string("hello world")).to eq("dlrow olleh")
          end
        end
  
        context 'when input is invalid' do
          it 'raises an error for non-string input' do
            expect { StringReverser.reverse_string(12345) }.to raise_error(ArgumentError, "Input must be a valid string.")
          end
  
          it 'raises an error for nil input' do
            expect { StringReverser.reverse_string(nil) }.to raise_error(ArgumentError, "Input must be a valid string.")
          end
        end
      end
    end
  end
  

Run this Code

Save the Ruby code in a file named StringReverser.rb and execute it using the command: ruby StringReverser.rb.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top