[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Getting user input at command line when script also takes arguments

Paul

4/24/2007 3:02:00 PM

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.

1 Answer

Sebastian Hungerecker

4/24/2007 3:24:00 PM

0

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 Hungerecker
--
Ist so, weil ist so
Bleibt so, weil war so