Home Ruby Exercises 1: Palindrome Detector
Post
Cancel

Ruby Exercises 1: Palindrome Detector

Since returning to freelance work (and after the global release of ChatGPT) I’m finding it near impossible to get a job coding..I suppose the world may generally be going in this direction and I’m just getting left out of the job market…again…boohoo. Anyway I don’t want to give up on the work I have done so far to become something of a software engineer, so I will persist in this, possibly fruitless, practice and re-learning of Ruby.

Here is a palindrome detection program - a ruby coding exercise, that will detect palidromes in strings and then give you a response from the terminal! Enjoy! The code repository is here

My first attempt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def palindrome(a_string)
  # check if a_string is a palindrome
  ispalindrome = true
  ispalindrome = false if a_string == ""
  cleaned_text = a_string.gsub(/[[:punct:] ]|!/, '').downcase
  string_half_length = (cleaned_text.length / 2).floor
  string_half_length.times do |index|
    ispalindrome = false if cleaned_text[index] != cleaned_text[cleaned_text.length - (1 + index)]
  end
  palindrome_detector_message = ispalindrome == true ? "#{a_string} is a palindrome" : "#{a_string} is not a palindrome"
  puts palindrome_detector_message
end

# Get the name from the command-line arguments
a_string = ARGV[0]

# Check if the name is provided
if a_string.nil?
  puts "Please provide a name as a command-line argument."
else
  palindrome(a_string)
end

And here is the better refactored version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def palindrome(a_string)
  just_letters = a_string.gsub(/[^a-zA-Z]/, "").downcase
  palindrome_detector_message = just_letters == just_letters.reverse ? "#{a_string} is a palindrome" : "#{a_string} is not a palindrome"
  palindrome_detector_message = just_letters.empty? ? " is not a palindrome" : palindrome_detector_message
  puts palindrome_detector_message
  return palindrome_detector_message
end

# Get the name from the command-line arguments
a_string = ARGV[0]

# Check if the name is provided
if a_string.nil?
  puts "Please provide a name as a command-line argument."
else
  palindrome(a_string)
end

Calling the method from a terminal can be done like this:

1
ruby palindrome_detector.rb oxo

Running the spec tests can be done like this:

1
bundle exec rspec spec/example_spec.rb
This post is licensed under CC BY 4.0 by the author.