-2

I'm coding a program that asks whether or not the user wants to give his name. If the user responds 'yes', the question is asked; on 'no' the program quits. If the users enter anything else, they are reminded to say either 'yes' or 'no'.

My code so far:

puts "Would you like to give us your name? (type yes or no)"
answer = gets.chomp

if answer == "yes"
  print "What's your name?"
  name = gets.chomp
  puts "Nice to meet you, #{name}"
elsif answer == "no"
  puts "Oh, ok. Good bye"
else
  puts "You need to answer yes or no"
end

I need start over, if the user does not enter 'yes' or 'no' for the initial question.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Check out the answers to this existing question on looping in Ruby: http://stackoverflow.com/questions/136793/is-there-a-do-while-loop-in-ruby – mikej Jan 12 '15 at 23:27

3 Answers3

2

You can solve that problem with a while loop, that breaks only when the correct input is made.

puts "Would you like to give us your name? (type yes or no)"
while answer = gets.chomp
  case answer
  when "yes"
    print "What's your name?"
    name = gets.chomp
    puts "Nice to meet you, #{name}"
    break
  when "no"
    puts "Oh, ok. Good bye"
    break
  else
    puts "You need to answer yes or no"
  end
end
lneb
  • 149
  • 4
0
answer = ""
while (answer != "yes" && answer != "no") do
  puts "Would you like to give us your name? (type yes or no)"
  answer = gets.chomp
end

if answer == "yes"
  print "What's your name?"
  name = gets.chomp
  puts "Nice to meet you, #{name}"
elsif answer == "no"
  puts "Oh, ok. Good bye"
else
  puts "You need to answer yes or no"
end
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
0

This would be better accomplished creating a Method

Something like this will work for you:

def getname
  # ask the user if we should continue
  puts "Would you like to give us your name? (type yes or no)"
  answer = gets.chomp

  if answer == "yes"
    # the user said yes. get the name
    print "What's your name?"
    name = gets.chomp
  elsif answer == "no"
    # the user said no. get out of here
    puts "Oh, ok. Good bye"
  else
    # the user didnt answer correctly
    puts "You need to answer yest or no"
    # so we call this very function again
    getname
  end
end

# call the above method that we created
getname

What we did here was wrap your code in a method declaration. In that very method declaration we call that very method if the user doesnt supply the expected input.

Hope this helps.

ptierno
  • 9,534
  • 2
  • 23
  • 35