-4

When I run this code in Sublime text, it enters an infinite loop instead of prompting user to 'Enter something'.

print 'Enter something'
input_user = gets.strip
if(input_user == 'something')
    puts 'You are smart'
else
    puts 'You are not'
end
  1. Can someone please help me understand why this is happening?
  2. Are there any other efficient ways to accept user input in ruby other than gets (without using third party libraries)?
zealouscoder
  • 96
  • 2
  • 3
  • 13
  • No way this code enters an infinite loop. There is _no magic_ in coding. Try to change first `print` to `puts` and see what’s happening. Maybe it’s your OS is too dumb. – Aleksei Matiushkin Sep 11 '18 at 06:06
  • Ok. What if you run the code in sublime text and try **command+b**? – zealouscoder Sep 11 '18 at 06:15
  • I do not run code from editors. Editors are made to edit the code, not to run it. – Aleksei Matiushkin Sep 11 '18 at 06:17
  • 1
    Ran this code. No infinite loop. – Ravi Teja Dandu Sep 11 '18 at 06:19
  • Cannot be reproduced as is. The infinite loop must be coming from somewhere other than what you wrote here, such as additional environment, script that calls this piece of code. – sawa Sep 11 '18 at 06:30
  • This code does not contain an infinite loop. Whatever's causing it _must_ be before the first line of your snippet. – Jules Sep 11 '18 at 06:41
  • 1
    The question makes it sound like you enter an infinite loop before you reach the first line of your code: "it enters an infinite loop **instead** of prompting user to 'Enter something'" – Simple Lime Sep 11 '18 at 06:43

3 Answers3

1

Sublime does not allow to input data, so it seems like an infinite loop. Also, you don't see Enter something because the output is "enqueued on the stream". You need to flush the output in order to see it. Look at this topic: How to print stdout immediately?

So, to see the first line printed in Sublime add STDOUT.flush after print (puts).

puts 'Enter something'
STDOUT.flush
input_user = gets.strip

Now, if you build from Sublime (CMD + B), you can see the first line printed, but the execution still hangs because Sublime does not pick up the input.

For a proper test run on terminal, there it works correctly, even without flushing.

iGian
  • 11,023
  • 3
  • 21
  • 36
0

There is no obvious reason why this code should lock into an infinite loop. I ran it just for kicks under ruby 2.4.1p111. Code runs as the described expectation, no infinite loop.

Dri
  • 492
  • 4
  • 13
0

It's not an infinite loop. It's just waiting for the input data.

It's quite the basic flow of a CLI app to ask the user for input:

And also using the #gets method to capture, store, and operator on that input.

Nuttapon
  • 101
  • 4