Forum: Ruby Getting user input at command line when script also takes ar

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B17d29d56cd9d4ccd91056eff4a355e3?d=identicon&s=25 Paul (Guest)
on 2007-04-24 17:06
(Received via mailing list)
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.
7a561ec0875fcbbe3066ea8fe288ec77?d=identicon&s=25 Sebastian Hungerecker (Guest)
on 2007-04-24 17:25
(Received via mailing list)
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
This topic is locked and can not be replied to.