Last active
December 11, 2016 22:17
-
-
Save descartez/08ba5fbc0ba9fb28713a046e9a8bc5ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
# Opens up string class, to allow these methonds to be called directly on the string rather than passed as a variable to a method. | |
def rev_string | |
# Splits the string into an array, for iterative purposes | |
str_arr = self.chars | |
# Builds a temporary array | |
tmp_arr = [] | |
str_arr.length.times do | |
# grabs the end of the str_array, and makes it the first of our new array | |
tmp_arr << str_arr.pop | |
end | |
# joins new array into strin | |
return tmp_arr.join | |
end | |
def palindrome? | |
# checks if proper length and if the first and last letters are equal, this keeps us from having to waste time reversing a string that wouldn't work as a palindrome | |
if self.length < 2 || self[0] != self[-1] | |
return false | |
else | |
# checks if a reversed string is equal to the unreversed string, method above | |
self == self.rev_string | |
end | |
end | |
end | |
puts "'aa' is palindrome? #{"aa".palindrome?}" | |
puts "'ca' is palindrome? #{"ca".palindrome?}" | |
puts "'a' is palindrome? #{"a".palindrome?}" | |
puts "'racecar' is palindrome? #{"racecar".palindrome?}" | |
puts "'racecare is palindrome?' #{"racecare".palindrome?}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment