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 ?
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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With