How can Ruby OptionParser take care of parameter with spaces? - ruby

I am trying to define the options for my Ruby script which sending messages from User A to User B for testing purpose. However I couldn't get it work when some of the option have spaces in the value. For example:
OptionParser.new do |opts|
opts.on("-p", "--params a=A,b=B,c=C", Array, "Parameters to compose the message") do |params|
options.params = params.map { |p| p.split("=") }
end
end
But when I try to specify thing like -p SENDER=foo,RECIPIENT=bar,BODY=foo bar it just gave me back ["SENDER" => "foo", "RECIPIENT" => "bar", "BODY" => "foo"].
I have also tried -p SENDER=foo,RECIPIENT=bar,BODY='foo bar' but no luck with it either.
Does OptionParser support this scenario?
Thank you!

Use single or double quotes to surround the parameter:
-p 'SENDER=foo,RECIPIENT=bar,BODY=foo bar'
For example:
require 'optparse'
options = {}
OptionParser.new do |opt|
opt.on('-p', '--params OPTS', Array) { |o| options[:p] = o }
end.parse!
require 'pp'
pp options # =>
Running that at the command-line using:
ruby test.rb --params 'SENDER=foo,RECIPIENT=bar,BODY=foo bar'
Outputs:
{:p=>["SENDER=foo", "RECIPIENT=bar", "BODY=foo bar"]}
This isn't an OptionParser issue, it's how the command-line works when parsing the options and passing them to the script. OptionParse only gets involved once it sees the argument 'SENDER=foo,RECIPIENT=bar,BODY=foo bar' and splits it on the commas into an array and passes that to the opt.on block:
'SENDER=foo,RECIPIENT=bar,BODY=foo bar'.split(',')
# => ["SENDER=foo", "RECIPIENT=bar", "BODY=foo bar"]
It looks like you're trying to split the incoming data into an array of arrays because of:
options.params = params.map { |p| p.split("=") }
I'd recommend considering converting it into a hash instead:
opt.on('-p', '--params OPTS', Array) { |o| options[:p] = Hash[o.map{ |s| s.split('=') }] }
Which results in:
{:p=>{"SENDER"=>"foo", "RECIPIENT"=>"bar", "BODY"=>"foo bar"}}
And makes it easy to get at specific entries passed in:
pp options[:p]['BODY'] # => "foo bar"

Related

How can I get info from user with OptionParser in Ruby?

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!
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.

How to get the specified option flag from within OptionParser

I'd like to get the exact option flag that was specified on the command line from within Ruby's OptionParser.
For example, suppose I have the following code:
parser = OptionParser.new {
|opts|
opts.on('-f', '--file FILE', 'filename') {
|arg|
$filename = arg
# Here I'd like to know whether '-f' or '--file' was entered
# on the command line.
}
# ... etc. ...
}
I'd like to know whether the user happened to type '-f' or '--file' on the command line. Is this possible without writing two separate opts.on blocks?
I don't think you can get the flags being passed in when inside the OptionParser.new block. At that point it's too late. However, prior to OptionParser parsing the command-line, it's possible to look and see what's being passed in.
ARGV contains the raw command-line. For instance, if this is the command-line invocation for some code:
foo -i 1 -j 2
then ARGV will contain:
["-i", "1", "-j", "2"]
and, then it becomes pretty easy to grab the flags:
ARGV.grep(/^-/) # => ["-i", "-j"]
There are other OptionParser-like tools for Ruby, and those might let you access the flags being used, but I can't think of a reason I'd ever care to. Looking at your code it seems like you're not understanding how to use OptionParser:
parser = OptionParser.new {
|opts|
opts.on('-f', '--file FILE', 'filename') {
|arg|
$filename = arg
# Here I'd like to know whether '-f' or '--file' was entered
# on the command line.
}
# ... etc. ...
}
Instead of doing it that way, I'd write it:
options = {}
OptionParser.new do |opts|
opts.on('-f', '--file FILE', 'filename') { |arg| options[:filename] = arg }
end.parse!
if options[:filename]
puts 'exists' if File.exist?(options[:filename])
end
Then, later in your code you can check in the options hash to see if either of the -f or --file options was given, and what the value was. That it was one or the other of -f or --file shouldn't ever matter.
If it does then you need to differentiate between the two flags, instead of treating them as if they're aliases:
options = {}
OptionParser.new do |opts|
opts.on('-f', 'filename') { |arg| options[:f] = arg }
opts.on('--file FILE', 'filename') { |arg| options[:file] = arg }
end.parse!
if options[:file] || options[:f]
puts 'exists' if File.exist?(options[:file] || options[:f])
end

How do I pass a hash from commandline?

I have a ruby script that has a hash.
Example:
animal_sound = { 'dog' => 'bark', 'cat' => 'meow' }
I want to add 'snake' => 'hiss'
Example:
myscript.rb --addsound "'snake' => 'hiss'"
Then in my script have it add it to animal_sound.
Example:
animal_sound.merge! 'snake' => 'hiss'
=> {"dog"=>"bark", "cat"=>"meow", "snake"=>"hiss"}
Is there a way to do this?
Here is the whole script:
#!/usr/bin/env ruby
require 'rubygems'
require 'micro-optparse'
options = Parser.new do |p|
p.option :addsound, "add sound"
end.process!
animal_sound = { 'dog' => 'bark', 'cat' => 'meow' }
if options[:add_sound]
newsound = options[:add_sound]
animal_sound.merge! newsound
end
puts animal_sound
When I run my script I get:
$ bin/myscript.rb --addsound "'snake' => 'hiss'"
bin/myscript.rb:14:in `merge!': can't convert true into Hash (TypeError)
from bin/myscript.rb:14:in `<main>'
SOLVED:
Using PSkocik's solution I got the script to work using animal, sound = options[:addsound].split(' => '); animal_sound[animal] = sound
I also used Simone Carletti's idea to simplify the CLI command. FYI it also works if I want to pass in hash format, like myscript.rb --addsound "'snake' => 'hiss'". Of course the split has to be changed back to split(' => '). I like the simpler CLI using the :.
Example:
myscript.rb --addsound snake:hiss
Final Code:
#!/usr/bin/env ruby
require 'rubygems'
require 'micro-optparse'
options = Parser.new do |p|
p.option :addsound, "add sound", default: ""
end.process!
animal_sound = { 'dog' => 'bark', 'cat' => 'meow' }
if options[:addsound]
animal, sound = options[:addsound].split(':')
animal_sound[animal] = sound
end
puts animal_sound
Command line:
$ bin/myscript.rb --addsound snake:hiss
{"dog"=>"bark", "cat"=>"meow", "snake"=>"hiss"}
I never could get the merge to work.
Each post was helpful. Thanks.
It's a good idea to keep the CLI interface detached from the underlying implementation. In fact, you may decide to switch the script in the future from Ruby to another language, and you don't really want to change the way the code is invoked.
My suggestion is to pass a serialized value, for example
myscript.rb --addsound snake:hiss
In the code, simply decompose the content and merge it.
if options[:add_sound]
animal, sound = options[:add_sound].split(":")
animal_sound.merge!(animal => sound)
end
p.option :addsound, "add sound"
^ this makes it a flag (true or false)
What you want is make it into a switch whose value is the next argument:
p.option :addsound, "add sound", default: ""
^ this makes it a switch, the string value will be assigned to options[:addsound]
newsound = options[:addsound]
^ Here you need to drop the underscore and parse the string into a hash.
Eval is evil.
For example, you could split it on ' => ' and forget about quoting:
newsound = [ options[:addsound].split(' => ') ].to_h #and then merge it
(Passing the argument like so --addsound snake:hiss and then splitting on ':' instead of ' => ' is another good option.)
^splitting on ' => ' should yield a two-member array. Here I put it into another array (arrays of two-member arrays are convertible to hashes) to make it convertible into a hash.
Or you do completely without merging and constructing another hash:
animal, sound = options[:addsound].split(' => ')
animal_sound[animal] = sound
In regards to your error
Notice the line if options[:add_sound]. That basically evaluates to if true. You are getting your error because you are setting newsound to true, and trying to merge a Boolean into a hash. To my knowledge, the .merge only works like so: hash1.merge(hash2).
Passing command line argument
Rather than passing the argument "'snake' => 'hiss'", I suggest making this a comma-delineated list, like so: "snake,hiss". From there, in your if options[:add_sound] block, you can split the string into an array, using a comma as a splitter. Finally, rather than using .merge, you can add your key:value as you normally would for any hash in Ruby. animal_sound[arr[0]] = arr[1].
Mind you, this method will work best with a single key:value pair. I am sure you can submit multiple pairs, but you would need to (by this method) split into more arrays by an additional character(like / maybe).

Parse command line arguments in a Ruby script

I want to call a Ruby script from the command line, and pass in parameters that are key/value pairs.
Command line call:
$ ruby my_script.rb --first_name=donald --last_name=knuth
my_script.rb:
puts args.first_name + args.last_name
What is the standard Ruby way to do this? In other languages I usually have to use an option parser. In Ruby I saw we have ARGF.read, but that does not seem to work key/value pairs like in this example.
OptionParser looks promising, but I can't tell if it actually supports this case.
Ruby's built-in OptionParser does this nicely. Combine it with OpenStruct and you're home free:
require 'optparse'
options = {}
OptionParser.new do |opt|
opt.on('--first_name FIRSTNAME') { |o| options[:first_name] = o }
opt.on('--last_name LASTNAME') { |o| options[:last_name] = o }
end.parse!
puts options
options will contain the parameters and values as a hash.
Saving and running that at the command line with no parameters results in:
$ ruby test.rb
{}
Running it with parameters:
$ ruby test.rb --first_name=foo --last_name=bar
{:first_name=>"foo", :last_name=>"bar"}
That example is using a Hash to contain the options, but you can use an OpenStruct which will result in usage like your request:
require 'optparse'
require 'ostruct'
options = OpenStruct.new
OptionParser.new do |opt|
opt.on('-f', '--first_name FIRSTNAME', 'The first name') { |o| options.first_name = o }
opt.on('-l', '--last_name LASTNAME', 'The last name') { |o| options.last_name = o }
end.parse!
puts options.first_name + ' ' + options.last_name
$ ruby test.rb --first_name=foo --last_name=bar
foo bar
It even automatically creates your -h or --help option:
$ ruby test.rb -h
Usage: test [options]
--first_name FIRSTNAME
--last_name LASTNAME
You can use short flags too:
require 'optparse'
options = {}
OptionParser.new do |opt|
opt.on('-f', '--first_name FIRSTNAME') { |o| options[:first_name] = o }
opt.on('-l', '--last_name LASTNAME') { |o| options[:last_name] = o }
end.parse!
puts options
Running that through its paces:
$ ruby test.rb -h
Usage: test [options]
-f, --first_name FIRSTNAME
-l, --last_name LASTNAME
$ ruby test.rb -f foo --l bar
{:first_name=>"foo", :last_name=>"bar"}
It's easy to add inline explanations for the options too:
OptionParser.new do |opt|
opt.on('-f', '--first_name FIRSTNAME', 'The first name') { |o| options[:first_name] = o }
opt.on('-l', '--last_name LASTNAME', 'The last name') { |o| options[:last_name] = o }
end.parse!
and:
$ ruby test.rb -h
Usage: test [options]
-f, --first_name FIRSTNAME The first name
-l, --last_name LASTNAME The last name
OptionParser also supports converting the parameter to a type, such as an Integer or an Array. Refer to the documentation for more examples and information.
You should also look at the related questions list to the right:
"Really Cheap Command-Line Option Parsing in Ruby"
"Pass variables to Ruby script via command line"
Based on the answer by #MartinCortez here's a short one-off that makes a hash of key/value pairs, where the values must be joined with an = sign. It also supports flag arguments without values:
args = Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?:=(\S+))?/) ]
…or alternatively…
args = Hash[ ARGV.flat_map{|s| s.scan(/--?([^=\s]+)(?:=(\S+))?/) } ]
Called with -x=foo -h --jim=jam it returns {"x"=>"foo", "h"=>nil, "jim"=>"jam"} so you can do things like:
puts args['jim'] if args.key?('h')
#=> jam
While there are multiple libraries to handle this—including GetoptLong included with Ruby—I personally prefer to roll my own. Here's the pattern I use, which makes it reasonably generic, not tied to a specific usage format, and flexible enough to allow intermixed flags, options, and required arguments in various orders:
USAGE = <<ENDUSAGE
Usage:
docubot [-h] [-v] [create [-s shell] [-f]] directory [-w writer] [-o output_file] [-n] [-l log_file]
ENDUSAGE
HELP = <<ENDHELP
-h, --help Show this help.
-v, --version Show the version number (#{DocuBot::VERSION}).
create Create a starter directory filled with example files;
also copies the template for easy modification, if desired.
-s, --shell The shell to copy from.
Available shells: #{DocuBot::SHELLS.join(', ')}
-f, --force Force create over an existing directory,
deleting any existing files.
-w, --writer The output type to create [Defaults to 'chm']
Available writers: #{DocuBot::Writer::INSTALLED_WRITERS.join(', ')}
-o, --output The file or folder (depending on the writer) to create.
[Default value depends on the writer chosen.]
-n, --nopreview Disable automatic preview of .chm.
-l, --logfile Specify the filename to log to.
ENDHELP
ARGS = { :shell=>'default', :writer=>'chm' } # Setting default values
UNFLAGGED_ARGS = [ :directory ] # Bare arguments (no flag)
next_arg = UNFLAGGED_ARGS.first
ARGV.each do |arg|
case arg
when '-h','--help' then ARGS[:help] = true
when 'create' then ARGS[:create] = true
when '-f','--force' then ARGS[:force] = true
when '-n','--nopreview' then ARGS[:nopreview] = true
when '-v','--version' then ARGS[:version] = true
when '-s','--shell' then next_arg = :shell
when '-w','--writer' then next_arg = :writer
when '-o','--output' then next_arg = :output
when '-l','--logfile' then next_arg = :logfile
else
if next_arg
ARGS[next_arg] = arg
UNFLAGGED_ARGS.delete( next_arg )
end
next_arg = UNFLAGGED_ARGS.first
end
end
puts "DocuBot v#{DocuBot::VERSION}" if ARGS[:version]
if ARGS[:help] or !ARGS[:directory]
puts USAGE unless ARGS[:version]
puts HELP if ARGS[:help]
exit
end
if ARGS[:logfile]
$stdout.reopen( ARGS[:logfile], "w" )
$stdout.sync = true
$stderr.reopen( $stdout )
end
# etc.
There is a number of command line arguments parsers in Ruby:
GetoptLong - Included in stdlib
OptionParser - No longer part of stdlib, since Ruby 3.0.0 converted to a separate optparse gem
slop
optimist
and many more...
Personally I'd choose slop or optimist, those are not part of standard Ruby installation.
gem install slop
But it offers simplicity and code readability. Assuming slightly more complex example with required arguments and default values:
require 'slop'
begin
opts = Slop.parse do |o|
o.int '-a', '--age', 'Current age', default: 42
o.string '-f', '--first_name', 'The first name', required: true
o.string '-l', '--last_name', 'The last name', required: true
o.bool '-v', '--verbose', 'verbose output', default: false
o.on '-h','--help', 'print the help' do
puts o
exit
end
end
p opts.to_hash
rescue Slop::Error => e
puts e.message
end
optimist formerly known as trollop, it's very easy to ready, with minimum boilerplate code:
gem install optimist
require 'optimist'
opts = Optimist::options do
opt :verbose, "verbose mode"
opt :first_name, "The first name", type: :string, required: true
opt :last_name, "The last name", type: :string, required: true
opt :age, "Current age", default: 42
end
p opts
Similar example using OptionParser:
#!/usr/bin/env ruby
require 'optparse'
require 'ostruct'
begin
options = OpenStruct.new
OptionParser.new do |opt|
opt.on('-a', '--age AGE', 'Current age') { |o| options.age = o }
opt.on('-f', '--first_name FIRSTNAME', 'The first name') { |o| options.first_name = o }
opt.on('-l', '--last_name LASTNAME', 'The last name') { |o| options.last_name = o }
opt.on('-v', '--verbose', 'Verbose output') { |o| options.verbose = true }
end.parse!
options[:age] = 42 if options[:age].nil?
raise OptionParser::MissingArgument.new('--first_name') if options[:first_name].nil?
raise OptionParser::MissingArgument.new('--last_name') if options[:last_name].nil?
options[:verbose] = false if options[:verbose].nil?
rescue OptionParser::ParseError => e
puts e.message
exit
end
GetoptLong parsing is even more complicated:
require 'getoptlong'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--first_name', '-f', GetoptLong::REQUIRED_ARGUMENT ],
[ '--last_name', '-l', GetoptLong::REQUIRED_ARGUMENT ],
[ '--age','-a', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--verbose','-v', GetoptLong::OPTIONAL_ARGUMENT ]
)
begin
options = {}
options[:verbose] = false
options[:age] = 42
opts.each do |opt, arg|
case opt
when '--help'
puts <<-EOF
usage: ./getlongopts.rb [options]
-a, --age Current age
-f, --first_name The first name
-l, --last_name The last name
-v, --verbose verbose output
-h, --help print the help
EOF
when '--first_name'
options[:first_name] = arg
when '--last_name'
options[:last_name] = arg
when '--age'
options[:age] = arg.to_i
when '--verbose'
options[:verbose] = arg
else
puts "unknown option `#{opt}`"
exit 1
end
end
raise GetoptLong::MissingArgument.new('Missing argument --first_name') if options[:first_name].nil?
raise GetoptLong::MissingArgument.new('Missing argument --last_name') if options[:last_name].nil?
rescue GetoptLong::Error => e
puts e.message
exit
end
puts options
Command line arguments was never meant to be a rocket science task, spend your time on reading/writing more useful code :)
I personally use Docopt. This is much more clear, maintainable and easy to read.
Have a look at the Ruby implementation's documentation for examples. The usage is really straightforward.
gem install docopt
Ruby code:
doc = <<DOCOPT
My program who says hello
Usage:
#{__FILE__} --first_name=<first_name> --last_name=<last_name>
DOCOPT
begin
args = Docopt::docopt(doc)
rescue Docopt::Exit => e
puts e.message
exit
end
print "Hello #{args['--first_name']} #{args['--last_name']}"
Then calling:
$ ./says_hello.rb --first_name=Homer --last_name=Simpsons
Hello Homer Simpsons
And without arguments:
$ ./says_hello.rb
Usage:
says_hello.rb --first_name=<first_name> --last_name=<last_name>
A bit of standard Ruby Regexp in myscript.rb:
args = {}
ARGV.each do |arg|
match = /--(?<key>.*?)=(?<value>.*)/.match(arg)
args[match[:key]] = match[:value] # e.g. args['first_name'] = 'donald'
end
puts args['first_name'] + ' ' + args['last_name']
And on the command line:
$ ruby script.rb --first_name=donald --last_name=knuth
Produces:
$ donald knuth
Here is a slight modification to #Phrogz excellent answer: this mod will allow you to pass a string with spaces in it.
args= Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?:="(.*?)"+)?/)]
In a command line pass the string like this:
ruby my_script.rb '--first="Boo Boo" --last="Bear"'
Or from another ruby script like this:
system('ruby my_script.rb \'--first="Boo Boo" --last="Bear"\'')
Results:
{"first"=>"Boo Boo", "last"=>"Bear"}
An improved version that handles arguments that are not options, arguments with a parameter, and -a as well as --a.
def parse(args)
parsed = {}
args.each do |arg|
match = /^-?-(?<key>.*?)(=(?<value>.*)|)$/.match(arg)
if match
parsed[match[:key].to_sym] = match[:value]
else
parsed[:text] = "#{parsed[:text]} #{arg}".strip
end
end
parsed
end

Ruby equivalent of perl's "Data::Dumper" for printing deep nested hashes/arrays

This is not a duplicate of Ruby equivalent of Perl Data::Dumper. That question is more than 3.5 years old and hence want to check are there any new options available in Ruby since then.
I am looking for perl's Dumper equivalent in ruby. I don't care what Dumper does behind the curtains. I have used it extensively for printing deep nested hashes and array in perl. So far I haven't found an alternative in ruby (Or I may not have find a way to make good use of available alternatives in Ruby).
This is my perl code and its Output:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my $hash;
$hash->{what}->{where} = "me";
$hash->{what}->{who} = "you";
$hash->{which}->{whom} = "she";
$hash->{which}->{why} = "him";
print Dumper($hash);
OUTPUT:
$VAR1 = {
'what' => {
'who' => 'you',
'where' => 'me'
},
'which' => {
'why' => 'him',
'whom' => 'she'
}
};
Just Love the Dumper. :)
In ruby, I tried pp, p, inspect and yaml. here is my same code in ruby and its output:
#!/usr/bin/ruby
require "pp"
require "yaml"
hash = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
hash[:what][:where] = "me"
hash[:what][:who] = "you"
hash[:which][:whom] = "she"
hash[:which][:why] = "him"
pp(hash)
puts "Double p did not help. Lets try single p"
p(hash)
puts "Single p did not help either...lets do an inspect"
puts hash.inspect
puts "inspect was no better...what about yaml...check it out"
y hash
puts "yaml is good for this test code but not for really deep nested structures"
OUTPUT:
{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
Double p did not help. Lets try single p
{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
Single p did not help either...lets do an inspect
{:what=>{:where=>"me", :who=>"you"}, :which=>{:whom=>"she", :why=>"him"}}
inspect was no better...what about yaml...check it out
---
:what:
:where: me
:who: you
:which:
:whom: she
:why: him
yaml is good for this test code but not for really deep nested structures
Thanks.
What about Awesome Print:
require 'awesome_print'
hash = {what: {where: "me", who: "you"}, which: { whom: "she", why: "him"}}
ap hash
Output (actually with syntax highlighting):
{
:what => {
:where => "me",
:who => "you"
},
:which => {
:whom => "she",
:why => "him"
}
}

Resources