Challenge 2 is pretty easy at first glance. At second glance…it’s also pretty easy. I took it upon myself to make this as difficult as I could, and I’m not sure why. Sometimes you get in a funk, and you have to bounce ideas off of people until you break out of it. Anyway, this prompt is pretty simple: ask the user to enter a string, count how many characters are in the string, and then return a string that has the user’s string and the number of characters contained within it.
For example:
One of the challenges is to make sure the user enters something into the prompt, and that’s when I started getting turned around. I already have a method that can enforce the kind of input goes into the prompt, but it felt like overkill for such a simple program. That method is the rescue-retry block:
def getString(prompt)
begin
puts prompt
string = gets.chomp
raise if string.empty?
rescue
puts "You must enter something to continue"
retry
end
string
end
string = getString("Please enter something")
Like I said, it seems like overkill. In an attempt to simplify, I cobbled together a more simple solution:
string = prompt = ""
while string.empty?
prompt = prompt.empty? == true ? "Please enter something" : "you must enter something to continue."
puts prompt
string = gets.chomp
end
It saves the string and prompt variables as an empty string on one line, and uses a while block to check if the string is empty. Then it uses a ternary operator to check to see if the prompt is an empty string. Since the basic prompt should only be used once, the program can use it’s value to see if the user has been asked this question. If prompt isn’t an empty string, then it knows to use the second, more informative prompt.
I got a little turned around while refactoring this code, and I’m glad my friend Matt was able to help me out a bit, let me bounce ideas off of him. The simplicity of this challenge illustrates how everyone can approach code problems differently, and how there are many correct ways to get an answer, depending on what the developer wants to communicate.