Reputation: 113
I tried to create a loop using a variable set to be boolean value true
. I was expecting the value to change to false
if a user inputs "exit"
, and the next iteration to not happen because the while
statement "isTrue == true"
is no longer true
.
isTrue = true
while isTrue == true do
input = gets
if input == "exit" then # exitと入力されたら
isTrue = false # プログラムを終了
else
puts "LOOPING..."
end
end
puts "ENDING NOW"
But it doesn't seem to be working and just keeps looping. Why isn't my code working?
Upvotes: 1
Views: 394
Reputation: 5552
Use gets.chomp
instead of gets
to remove tailing "\n" and it will work. So you will not deal with "exit\n" coming from gets
Upvotes: 2
Reputation: 959
Your program can be made more compact:
while gets.chomp != 'exit' do
puts 'LOOPING...'
end
puts 'ENDING NOW'
This version of the program does exactly the same thing as yours, but is much smaller and faster.
Good luck in your Ruby learning!
Upvotes: 0
Reputation: 2572
rstrip
will help you in this case.
Your input is actually not exactly "exit", since you press the return button.
The below code will work.
isTrue = true
while isTrue == true do
input = gets
if input.rstrip == "exit" then # exitと入力されたら
isTrue = false # プログラムを終了
else
puts "LOOPING..."
end
end
puts "ENDING NOW"
Refer - Standard Docs
Upvotes: 0
Reputation: 5252
[1] pry(main)> input = gets
exit
=> "exit\n"
[2] pry(main)>
It's because gets
input will contain a \n
in it. You need dealing with it.
Like this:
[2] pry(main)> input.chomp
=> "exit"
Usually ppl write like this:
[3] pry(main)> input = gets.chomp
exit
=> "exit"
Upvotes: 0