Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby IF no ARGV given

Tags:

ruby

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 ?

like image 784
Ba7a7chy Avatar asked Jan 30 '13 17:01

Ba7a7chy


3 Answers

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.

like image 108
Dave Newton Avatar answered Nov 14 '22 07:11

Dave Newton


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?
like image 39
Wayne Conrad Avatar answered Nov 14 '22 06:11

Wayne Conrad


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
like image 30
Marten Veldthuis Avatar answered Nov 14 '22 07:11

Marten Veldthuis