I don know if it's your problem, but you don't need the == true
.
if ARGV.include? '-v'
puts "Do junk"
else
puts "Nope"
end
The include?
method returns true
or false
.
質問
I am having some issues searching for what options have been passed in the ARGV. I have,
if ARGV.include? '-v' == true
puts "Do junk"
else
puts "Nope"
end
This seems like a shockingly simple thing but I always get "Nope" either when I place "-v" or when I do not. Am I missing something simple here?
解決
I don know if it's your problem, but you don't need the == true
.
if ARGV.include? '-v'
puts "Do junk"
else
puts "Nope"
end
The include?
method returns true
or false
.
他のヒント
Why are you searching ARGV for options? Use the standard library's OptionParser class, which is made for this.
require 'optparse'
require 'pp'
options = {}
OptionParser.new { |opt|
opt.on('-v', '--verbose', 'Be verbose') { |o| options[:verbose] = o }
}.parse!
pp options
Save that, and run it with something like: ruby test.rb -v
or ruby test.rb --verbose
and you'll see:
{:verbose=>true}
Run it with ruby test.rb -h
or ruby test.rb --help
and you'll see:
Usage: test [options]
-v, --verbose Be verbose
OptionParser has all sorts of nice (and intelligent) tricks for setting booleans, required parameters, coercing values so you can get multiple values for a parameter returned as an array, etc. And, notice that it created the help for me, including using -h
or --help
for the flag.
Look at the examples in the documentation for additional ideas of what it can do.
This is a precedence problem. Write as'
if ARGV.include?('-v') == true
puts "Do junk"
else
puts "Nope"
end
In your case if ARGV.include? '-v' == true
has been interpreted as if ARGV.include?
('-v' == true)
. Now '-v' == true
returns false
, and false
is not included in your ARGV
array, so if
evaluates as false
, and else
part is getting executed.
Better to write as
if ARGV.include? '-v'
puts "Do junk"
else
puts "Nope"
end
Because ARGV
is an array, and Array#include?(ob)
returns true
, if the ob
found inside the array.
All of the other answers so far are right in that it's a precedence problem.
Here are a couple helpful notes, the first of which has already been touched on:
You don't need == true
, since the include?
method already returns true or false.
For parsing command-line arguments, you might find it more intuitive to use a library like Trollop. Using Trollop, your example could be done like this:
require 'trollop'
opts = Trollop::options do
opt :verbose, "Run verbosely" # (-v is created automatically from this)
end
if opts[:v]
puts "yes"
else
puts "no"
end
(EDIT: See also the Tin Man's answer re: optparse)