0

I am writing a program in which I am taking in a csv file via the < operator on the command line. After I read in the file I would also like to ask the user questions and have them input their response via the command line. However, whenever I ask for user input, my program skips right over it.

When I searched stack overflow I found what seems to be the python version here, but it doesn't really help me since the methods are obviously different.

I read my file using $stdin.read. And I have tried to use regular gets, STDIN.gets, and $stdin.gets. However, the program always skips over them.

Sample input ruby ./bin/kata < items.csv Current File

require 'csv'

n = $stdin.read
arr = CSV.parse(n)
input = ''
while true
  puts "What is your choice: "
  input = $stdin.gets.to_i
  if input.zero?
    break
  end
end

My expected result is to have What is your choice: display in the command and wait for user input. However, I am getting that phrase displayed over and over in an infinite loop. Any help would be appreciated!

2 Answers2

0

You can't read both file and user input from stdin. You must choose. But since you want both, how about this:

Instead of piping the file content to stdin, pass just the filename to your script. The script will then open and read the file. And stdin will be available for interaction with the user (through $stdin or STDIN).

Here is a minor modification of your script:

arr = CSV.parse(ARGF) # the important part. 
input = ''
while true
  puts "What is your choice: "
  input = STDIN.gets.to_i
  if input.zero?
    break
  end
end

And you can call it like this:

ruby ./bin/kata items.csv

You can read more about ARGF in the documentation: https://ruby-doc.org/core-2.6/ARGF.html

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

This has nothing to do with Ruby. It is a feature of the shell.

A file descriptor is connected to exactly one file at any one time. The file descriptor 0 (standard input) can be connected to a file or it can be connected to the terminal. It can't be connected to both.

So, therefore, what you want is simply not possible. And it is not just not possible in Ruby, it is fundamentally impossible by the very nature of how shell redirection works.

If you want to change this, there is nothing you can do in your program or in Ruby. You need to modify how your shell works.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653