Reputation: 45
For example, when I type ruby file.rb -a "water the plants"
in command line
I want this line to be added on a hash. Such as a to-do list.
So it will look something like item1: water the plants
Here's what I did so far:
require 'optparse'
option_parser = OptionParser.new do |opts|
opts.on '-a', '--add',
end
Thanks in advance!
Upvotes: 0
Views: 143
Reputation: 26768
Look a bit more closely at the examples in the docs for OptionParser.
To accept a value for an argument, you have to specify it in the second argument to opts.on
, something like this:
require 'optparse'
option_parser = OptionParser.new do |opts|
opts.on '-a', '--add val' do |value|
puts value
end
end.parse!
To make it a required argument, just change that val
to capitalized VAL
(it can be any word, I'm just using "val" as an example).
Calling it, you can see how it works:
ruby file.rb -a "water the plants"
# => "water the plants"
ruby file.rb -a "water the plants" "do the dishes"
# => "water the plants"
ruby file.rb -a "water the plants" -a "do the dishes"
# => water the plants
# => do the dishes
As you can see, to pass multiple values, you need to include the -a
flag multiple times. The block is called for each value individually.
Upvotes: 1