# Getting user input at command line when script also takes ar

**URL:** <https://www.ruby-forum.com/t/getting-user-input-at-command-line-when-script-also-takes-ar/92820>\
**Category:** Ruby\
**Created:** [April 24, 2007, 5:06pm UTC](https://www.ruby-forum.com/t/getting-user-input-at-command-line-when-script-also-takes-ar/92820 "2007-04-24T17:06:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![paul](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bbe5ce/32.png) [@paul](https://www.ruby-forum.com/u/paul)\
**Post date:** [April 24, 2007, 5:06pm UTC](https://www.ruby-forum.com/t/getting-user-input-at-command-line-when-script-also-takes-ar/92820/1 "2007-04-24T17:06:17Z")

</div>

I’ve got this short script that scans a directory of files for a  
particular phrase that’s input by the user at the command prompt. I’m  
not sure if I’m getting the user input correctly because I’ve noticed  
that Ruby likes to give me errors more often than not.

## Here’s the script:

if ARGV[0].nil?  
puts “usage: #{$0} [directory to scan]”  
exit  
end  
scandir = ARGV[0]

print "Enter text to search for : "  
search\_string = gets  
search\_string.chomp!

## puts "string to search for = " + search\_string

## When I run the script with an argument of ‘temp’, I get the following error:

## Enter text to search for : C:/scripts/zz\_test2.rb:8:in `gets’: No such file or directory - temp (Errno::ENOENT) from C:/scripts/zz\_test2.rb:8

I tried switching line 5 to : scandir = ARGV.shift  
-\> The script now correctly prompts the user to enter some text.

However, if I enter 2 (or more) arguments on the command line, I get  
the same error as above (Errno::ENOENT).

Can someone please tell me what’s a good way to get user input for a  
script that also requires command line arguments? (BTW, I would  
prefer to stick to standard Ruby libraries so that the script is  
easily portable across different computers.)

TIA. Paul.

---

<div class="post-metadata">

**Author:** ![paul](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bbe5ce/32.png) [@paul](https://www.ruby-forum.com/u/paul)\
**Post date:** [April 24, 2007, 5:25pm UTC](https://www.ruby-forum.com/t/getting-user-input-at-command-line-when-script-also-takes-ar/92820/2 "2007-04-24T17:25:20Z")

</div>

Paul wrote:

> Can someone please tell me what’s a good way to get user input for a  
> script that also requires command line arguments?

Use STDIN.gets instead of Kernel#gets. Kernel#gets reads the input from  
files  
if any were given as command line parameters and only reads from STDIN  
if  
there weren’t. STDIN.gets always reads from STDIN.

HTH,  
Sebastian H.
