Berlin Berlin - 2 months ago 25
Ruby Question

Ruby raise exception if ARGV is empty or nil

This is my code:

region = ARGV[0]
instance_name = ARGV[1]


This way its works:

raise RuntimeError, 'empty argument' if ARGV[0].nil?
raise RuntimeError, 'empty argument' if ARGV[1].nil?


This way its not works:

I tried all of them

ARGV.each do |a|
raise RuntimeError, 'empty argument' if "#{a}".nil?
raise RuntimeError, 'empty argument' if a.nil?
raise RuntimeError, 'empty argument' if "#{a}".empty?
raise RuntimeError, 'empty argument' if a.empty?
end


How should I do that ?

Thanks.

Answer

raise RuntimeError, 'empty argument' if ARGV[0].nil? works because an attempt to access any index in a Ruby array that doesn't exist will return nil.

ARGV[123213] #=> nil

ARGV.each will attempt to loop over the contents of ARGV but if ARGV is empty the contents of the block will never be executed so none of your if conditions will actually be run.

If you want to check that 2 arguments have been provided you can check the length ARGV.length == 2.

It is technically possible that an empty string has been passed for one of the arguments. For instance if the script is run using

ruby myscript.rb ""

So you can check

if ARGV.length == 2 && ARGV.none?(&:empty?)
  # 2 arguments provided...
Comments