Skip to content

Instantly share code, notes, and snippets.

@prio101
Created May 1, 2025 07:52
Show Gist options
  • Save prio101/f8a5a654b066bf6c4a1e75ee4d65fa53 to your computer and use it in GitHub Desktop.
Save prio101/f8a5a654b066bf6c4a1e75ee4d65fa53 to your computer and use it in GitHub Desktop.
Reverse String
require 'minitest/autorun'
# Implementation of my_reverse method
# This method takes a string as input and returns the string in reverse order.
# The method also handles edge cases such as empty strings and single-character strings.
# The method uses a loop to iterate through the string in reverse order and constructs the reversed string.
# Custom error class for handling invalid input types
# This class inherits from StandardError and provides a custom error message.
# It is raised when the input to the my_reverse method is not a string.
class ReverseDataTypeError < StandardError
def message
'Input must be a string'
end
end
# my_reverse method implementation
def my_reverse(string)
# check if string is empty or actually a string or string is nil
raise ReverseDataTypeError unless string.is_a?(String)
return '' if string.empty?
# check if string is a single character
return string if string.length == 1
reversed_string = ''
string.length.times do |i|
reversed_string += string[string.length - 1 - i]
end
reversed_string
rescue ReverseDataTypeError => e
puts "Error: #{e.message}\n"
''
end
# test cases without minitest
puts my_reverse('') # ''
puts my_reverse('a') # 'a'
puts my_reverse('ab') # 'ba'
puts my_reverse('abc') # 'cba'
puts my_reverse('abcd') # 'dcba'
puts my_reverse(123456) # ''
puts my_reverse('ab' * 1000) # 'ba' * 1000
puts my_reverse(nil) # ''
# test cases with minitest
class TestMyReverse < Minitest::Test
def test_empty_string
assert_equal '', my_reverse('')
end
def test_single_character
assert_equal 'a', my_reverse('a')
end
def test_two_characters
assert_equal 'ba', my_reverse('ab')
end
def test_three_characters
assert_equal 'cba', my_reverse('abc')
end
def test_four_characters
assert_equal 'dcba', my_reverse('abcd')
end
def test_integer_input
assert_equal '', my_reverse(123456)
end
def test_nil_input
assert_equal '', my_reverse(nil)
end
def test_large_string
assert_equal 'ba' * 1000, my_reverse('ab' * 1000)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment