Ludovico Zocchi
Ludovico Zocchi

Reputation: 19

Why do I get stuck in this While loop?

While loop in Ruby
I think the problem is pretty simple but I don't really understand it. When I answer the correct option, so it can be 'Even' or 'Uneven', it repeatedly ask me the question. It think the problem is with the or operator

puts 'Which numbers do you want to see, the even or uneven ones?'
answer = gets.chomp
    
 while answer != 'Uneven' or answer != 'Even'
   puts 'Please answer Even or Uneven.'
   answer = gets.chomp
 end

Is there a way to write a while loop with 2 options like here?

Upvotes: 1

Views: 103

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Firstly, the conditions should be connected by and instead of or.

puts 'Which numbers do you want to see, the even or uneven ones?'
answer = gets.chomp

while answer != 'Even' and answer != 'Uneven'
  puts 'Please answer Even or Uneven.'
  answer = gets.chomp
end

Secondly, the code can be improved further:
Do not repeat yourself: move gets.chomp inside the loop.
Add downcase, so that the user can enter the string in a case-insensitive way, e.g., odd, Odd, etc.
Make an infinite loop using loop do ... end and use break with an if to exit the loop more easily.
The loop creates a separate scope, so we need to make cur_answer visible in the outer scope. For this, make the loop return the cur_answer by using break cur_answer (break with an argument returns that argument).
Replace the repetitive != operators using an array of desired values and include?. The array of strings can be easily created using Percent Strings, here %w[...].

#!/usr/bin/env ruby

puts 'Which numbers do you want to see, even or odd ones?'

answer = loop do
  cur_answer = gets.chomp.downcase
  break cur_answer if %w[ even odd ].include? cur_answer
  puts 'Please answer even or odd.'
end

puts "answer=#{answer};"

Upvotes: 2

Related Questions