SirPuffingtons
SirPuffingtons

Reputation: 1

'gets' doesn't wait for user input

I'm attempting to develop a program on repl.it using its Ruby platform. Here's what I've got:

puts "Copy the entire request page and paste it into this console, then 
hit ENTER."
request_info = gets("Edit Confirmation").chomp.gsub!(/\s+/m, ' 
').strip.split(" ")

puts "What is your name?"
your_name = gets.chomp
puts "Thanks, #{your_name}!"

The way I've got it, the user pastes a multi-line request, which ends with "Edit Confirmation", and then it splits the request, word-by-word, into its own array for me to parse and pull the relevant data.

But I can't seem to use the gets command a second time after initially inquiring the user for a multi-line input at the start. Any other gets command I attempt to use after that is skipped, and the program ends.

Upvotes: 0

Views: 693

Answers (1)

Tom Lord
Tom Lord

Reputation: 28285

Your code is doing something quite unusual: By passing a string to the gets method, you are actually changing the input separator:

gets(sep, limit [, getline_args]) → string or nil

Reads the next “line'' from the I/O stream; lines are separated by sep.

The reason why your code is not working as you expect is because a trailing "\n" character is left in the input buffer - so calling gets a second time instantly returns this string.

Perhaps the easiest way to resolve this would just be to absorb this character in the first gets call:

request_info = gets("Edit Confirmation\n").chomp.gsub!(/\s+/m, ' ').strip.split(" ")

For a "complex" multi-line input like this, it would be more common to pass a file name parameter to the ruby script, and read this file rather than pasting it into the terminal.

Or, you could use gets(nil) to read until an EOF character and ask the user to press CTRL+D to signify the end of the multi-line input.

Upvotes: 4

Related Questions