0

I have a function that is suppose to force user to enter the values from yes/no/y/n. If user enter any other value then it should prompt the user for INVALID ENTRY message but it is not handling the else block as expected. Can someone let me know what's going wrong here?

def handleYesNo(value)
    begin
        val = ""

        while("#{value}" != "")
             if ("#{value.downcase}" == "yes" || "#{value.downcase}" == "y" || "#{value.downcase}" == "no" || "#{value.downcase}" == "n")
                    val = value
                    break
             else
                     puts "INVALID ENTRY"
             end
         end

         val

      rescue => e
           puts "Exception occurred - #{e}.".red
      end
end

4 Answers 4

2

If you pass anything except yes/no/y/n to this method it will loop forever. It is because you have no break in the else block.

Maybe you want to prompt the user again? You could pass a boolean from the method to indicate if it was a success or not. And then you can take care of it is the calling code. Also the need for looping disappears in this scope.

Sidenote: you could rewrite the if criteria as:

['y','n','yes','no'].include? value.downcase
Sign up to request clarification or add additional context in comments.

Comments

1

It looks like the problem is that the user is never prompted to input a new value. This means that if the value argument that's passed in is good, it will break, but will otherwise loop forever, since value will not be empty (the while loop condition) and it will never be reset to what you're looking for. I'd reccomend something like this:

def handleYesNo(value)
  val = ""

  while("#{value}" != "")
    if ['yes', 'y', 'no', 'n'].include?(value.downcase)
      val = value
    else
      puts "INVALID ENTRY, Enter new value: "
      value = gets.chomp
    end
  end

  val
end

Comments

1
answer = "" # the empty string

while answer != "yes" and answer != "y" and answer != "no" and answer != "n" do
  answer = gets.chomp
  if answer != "yes" and answer != "y" and answer != "no" and answer != "n" 
    puts "INVALID ENTRY"
  end
end

Comments

1

For the sake of variety, here's another option. There's a gem called interact which does command-line prompting for you.

class MyCommandLine
  include Interactive

  def run
    ask "Is this cool?", choices: ["yes", "no"]
  end
end

Then when you run it as MyCommandLine.new.run it will prompt you, repeat questions as necessary, and automatically accept short answers (like "y" or "n") when they are sufficient to differentiate. There are even a few advanced features like rewind (when you enable this, a user hits the up arrow to revisit questions).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.