itsh
itsh

Reputation: 1123

Could not handle else block inside while loop

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

Upvotes: 0

Views: 48

Answers (4)

Mark Thomas
Mark Thomas

Reputation: 37507

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).

Upvotes: 1

adamwellsdev
adamwellsdev

Reputation: 91

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

Upvotes: 1

Ian
Ian

Reputation: 3898

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

Upvotes: 1

froderik
froderik

Reputation: 4808

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

Upvotes: 2

Related Questions