All right, I have the programming aptitude of a goldfish, so I could use some help. I have the following code (please excuse my terrible sense of humor):

puts 'Do you have a middle name?'
answer=gets.chomp.downcase
 while true 
 if answer != ('yes' || 'no')
  puts 'Yes or no answers only, dumbass.'
  puts 'So I\'ll ask again. Do you have a middle name?'
  answer=gets.chomp.downcase
elsif answer == ('yes' || 'no')
if answer == 'yes'
  puts 'Cool. What is it?'
  middlename=gets.chomp
  puts middlename +'? That\'s dumb.'
  break
if answer == 'no'
  puts 'I guess you aren\'t cool enough.'
  break
end
end
end
end
puts 'Well, smell ya later.'

It works mostly fine, but I have one problem: choosing the no option. I cannot figure out how to get that to work. It will loop fine, and choosing the yes option works.

Basically, my question is: how do I create a loop with two break options?

有帮助吗?

解决方案

For something like this you should use a case/when which is a Ruby switch statement because having all of those if/end blocks will get confusing fast.

Also please read this guide: https://github.com/bbatsov/ruby-style-guide It will teach you how to properly format your ruby code.

puts 'Do you have a middle name?'
answer=gets.chomp.downcase

case answer
when 'yes' 
  puts 'Cool. What is it?'
  middlename=gets.chomp
  puts middlename +'? That\'s dumb.'
when 'no'
  puts 'I guess you aren\'t cool enough.'
else  
  puts 'Yes or no answers only, dumbass.'
  puts 'So I\'ll ask again. Do you have a middle name?'
  answer=gets.chomp.downcase
end

puts 'Well, smell ya later.'

And if you always want it to loop when they don't answer yes or no. You can do that by wrapping the code block in a loop as follows:

puts 'Do you have a middle name?'
answer=gets.chomp.downcase

loop do
  case answer
  when 'yes' 
    puts 'Cool. What is it?'
    middlename=gets.chomp
    puts middlename +'? That\'s dumb.'
    break
  when 'no'
    puts 'I guess you aren\'t cool enough.'
    break
  else  
    puts 'Yes or no answers only, dumbass.'
    puts 'So I\'ll ask again. Do you have a middle name?'
    answer=gets.chomp.downcase
  end
end

puts 'Well, smell ya later.'

See this answer: How to write a switch statement in Ruby

其他提示

if answer != ('yes' || 'no') isn't doing what you think it is. Since 'yes' is non-nil, which is true, the logical OR is short-circuited and the value of the parenthetic expression is always 'yes'. Try if answer != 'yes' && answer != 'no' instead.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top