Ba7a7chy
Ba7a7chy

Reputation: 1521

Ruby IF no ARGV given

This is my code:

if ARGV[0] == false
    puts "Usage: ./script.rb argument"
    exit
end
print "Yey we got an argument: " ARGV[0]

But I just cant make the code check if ARGV[0] is given or not, how should I do that ?

Upvotes: 17

Views: 23948

Answers (7)

rld
rld

Reputation: 2763

I do this and work's:

url = ARGV[0] 

if url.nil?
  puts "The shell script needs the arguments."
  exit
end

Upvotes: 0

Harichandan Pulagam
Harichandan Pulagam

Reputation: 368

To check if ARGV[0] (or more args) is given or not:

puts 'Usage: ...' if ARGV.length == 0

You could also use ARGV.empty? (@DaveNewton's answer)

Upvotes: 1

KomodoDave
KomodoDave

Reputation: 7319

Here's what I do:

a = 'defaultvalue' if (a = ARGV.shift).nil?

Someone else suggested this:

a = ARGV.shift || 'defaultvalue'

This is wrong, since any false value will cause defaultvalue to be assigned, e.g.:

args=[false]; a=args.shift||true; # a has final value true when it should be false

Upvotes: -2

Marten Veldthuis
Marten Veldthuis

Reputation: 1910

I realize a good solution is already given, but nobody mentioned the real reason why your example didn't work.

The issue with your example code is that if there are no arguments given, ARGV[0] will return nil, and nil == false is false. nil is "falsy", but not equal to false. What you could have done is:

unless ARGV[0]
  puts "Usage: ..."
  exit 1
end

Which would have worked, because this statement now depends on falsyness, rather than on equality to the actual false.

But don't use this code, it's far more clear if you state your actual intent, which is that you want to know if there are any arguments (instead of whether the first argument is falsy). So use the code others suggested:

if ARGV.empty?
  puts "Usage..."
  exit 1
end

Upvotes: 6

Dave Newton
Dave Newton

Reputation: 160211

Check if it's empty? (or check its length):

if ARGV.empty?
  puts ...
  exit
end

Consider using any of the Ruby command line argument parsers, like OptionParser.

Upvotes: 32

Wayne Conrad
Wayne Conrad

Reputation: 108049

The simplest way to process positional arguments (other than using a gem to do it) is to shift them off, one at a time:

arg1 = ARGV.shift
arg2 = ARGV.shift

A missing argument will be nil. Let's exploit that to give arg2 a default value:

arg1 = ARGV.shift
arg2 = ARGV.shift || 'default value goes here'

Checking for a required argument is trivial:

raise "missing argument" unless arg1

It's also easy to see if too many arguments have been supplied:

raise "too many arguments" unless ARGV.empty?

Upvotes: 7

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230396

You can check the length of ARGV. If it has zero elements then ARGV[0] wasn't given.

Upvotes: 0

Related Questions