Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a program test.rb I want to be able to pass arguments to the program, much like you can do in the C language. For example:
ruby test.rb param1
Is there a way I can do this?
Use ARGV
The special ARGV array contains the arguments passed to a Ruby script. For example:
$ ruby -e 'puts ARGV.inspect' param1
["param1"]
See also ARGF#argv.
Ruby has a lib included that handles command line option: Options Parser
http://ruby-doc.org/stdlib-2.0.0/libdoc/optparse/rdoc/OptionParser.html
A simple example ruby program:
require 'optparse'
# create hash to hold program options
program_options = {}
# Parse the options passed into via command line
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
# Run Program Code
# ...
# your program will have access to the program_options hash
then run the program with ruby example.rb -v
opts.on has many options for detecting long (i.e., --verbose) and short (i.e., -v) switches, as well as accepting input and optional switches
Related
I am writing a script with different options in ruby, and I can't understand how the OptionParser could help me.
In particular, there is an example in the documentation: https://docs.ruby-lang.org/en/2.1.0/OptionParser.html
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
p options
p ARGV
I can understand the exclamation mark on the "end.parse" line (but I expected a parameter after that), but I find the following 2 lines confusing, p hasn't been declared, and I can't understand if it's part of the example source.
And how do I use the '-v' option? Do I simply check if options[:v] is nil or true?
Last thing, what happens to the other options? Does the OptionParser only parse switches? What if I had other parameters after the '-v'? Like myscript -v duck ketchup banana?
To answer your questions:
I can understand the exclamation mark on the "end.parse" line (but I expected a parameter after that)
The documentation states that parse! takes an optional argv parameter. If it is not supplied, it defaults to default_argv, which I imagine is the string containing the arguments passed to this script in the command line.
p hasn't been declared, and I can't understand if it's part of the example source
p is defined in Kernel, so it is (almost) always available in Ruby. p obj is equivalent to puts obj.inspect.
In this context, p is just used to illustrate that after parsing the arguments, the options hash contains all the flags/options you defined in the OptionParser block.
And how do I use the '-v' option? Do I simply check if options[:v] is nil or true?
Yes, but that would actually be options[:verbose].
Last thing, what happens to the other options? Does the OptionParser only parse switches? What if I had other parameters after the '-v'? Like myscript -v duck ketchup banana?
You will have to make multiple calls to opts.on to match all the other switches/arguments you are interested in. Look at the documentation here for explanations on how to do that.
I have a Ruby app with a relatively broad set of command-line arguments. I would like to suppress "short" variants for a number of options so that they can only be used in the long ("double dash") form.
Can I somehow suppress short dash variants for some options?
UPDATE 2013/10/08
It turned out that indeed omitting the short variant works! However, for me it didn't because for some reason in my program all the short keys were prefixed with a space. So a simple case like this:
require 'optparse'
op = OptionParser.new
op.on(" -f", "--from FORMAT", "Use the specific format") {}
op.on("--flip", "Do a flip") {}
op.parse!
caused the exception:
ruby why.rb -f some-foos
why.rb:17:in `<main>': ambiguous option: -f (OptionParser::AmbiguousOption
while the advice given (note the lack of space after the opening quote):
require 'optparse'
OptionParser.new do |opts|
opts.on("-d", "--ding DING", "Should not conflict with dangerous-option") do
puts "ding set!"
end
opts.on("--dangerous-option", "Set dangerous option") do |v|
puts "dangerous option set to #{v}"
end
end.parse!
works fine.
$ruby dang.rb -d xyz
ding set!
So thanks p11y for pointing me in the right direction with a working example. Also, if this "leading space" is in place, optparse will not complain - but it will change the interpretation of your short keys (or, better to say, will ignore them and show them as part of your help line! - and still use the auto-generated keys instead).
Just drop the short form:
require 'optparse'
OptionParser.new do |opts|
opts.on("--dangerous-option", "Set dangerous option") do |v|
puts "dangerous option set to #{v}"
end
end.parse!
$ ruby foo.rb -h
Usage: foo [options]
--dangerous-option Set dangerous option
$ ruby foo.rb --dangerous-option
dangerous option set to true
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Where are these symbols defined, and what are they used for?
:w2_end
:w2_beg
:w1_beg
:w1_end
I found those in my IRB by using the line Symbol.all_symbols .
My Ruby version and IRB versions are:
C:\>ruby -v
ruby 1.9.3p374 (2013-01-15) [i386-mingw32]
C:\>irb --version
irb 0.9.6(09/06/30)
I tried the same in another Ruby and IRB version as below:
C:\>irb --version
irb 0.9.6(09/06/30)
C:\>ruby -v
ruby 1.9.3p392 (2013-02-22) [i386-mingw32]
Arr = Symbol.all_symbols
Arr.include?(:w2_end) #=> true
Arr.include?(:w2_beg) #=> true
Arr.include?(:w1_beg) #=> true
Arr.include?(:w1_end) #=> true
These symbols don't appear in the Ruby source, nor are they defined when I look for them:
$ rvm 1.9.3-p374 do irb
1.9.3p374 :003 > Symbol.all_symbols.map(&:to_s).grep(/^w\d/)
=> []
Have you got your irb configured to load any extensions? Look in your .irbrc, if you have one.
Those symbols are commonly found in, among other places, readline libraries. irb uses readline. Perhaps there's something special about readline on Windows (it being coded in Ruby, for example) that causes those symbols to be defined.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I was attempting to do what I thought should be a very basic script as my first bit of ruby code. Perhaps someone can help me out with what's going on.
./delete_file.rb: line 3: puts: command not found
./delete_file.rb: line 4: auth_token: command not found
./delete_file.rb: line 6: puts: command not found
User1$ cat delete_file.rb
# /usr/bin/ruby
# Delete file script
puts "Enter current token"
auth_token = gets.chomp
puts "data goes here" + auth_token + "more data here"
first line of file should be:
#!/usr/bin/ruby
I'm new to ruby ... wondering if the following is possible:
I currently run a test app within irb (irb -r test.rb) and manually execute
various command implemented in test.rb. One of these functions is currently implemented as follows:
def cli(cmd)
ret=$client.Cli(cmd)
print ret, "\n"
end
Where $client.Cli() takes a string. I currently type the following in the IRB prompt
> cli "some command with parameters"
This is sent over socket and results are returned
I would like to be able to do this WITHOUT the quotes. This would be just for this command
Is there a way to do this generally in ruby? if not how would you extend irb to do this?
For those who know 'C' this would be like the following:
#define CLI(CMD) cli(#CMD)
CLI(Quadafi and Sheen walk into a bar...)
where the pre-processed output is:
cli("Quadafi and Sheen walk into a bar...")
Thanks
You could actually monkey patch the gets method of the IRB::StdioInputMethod and IRB::ReadlineInputMethod classes, and perform a rewrite if the cli method is called, by adding the following to your test.rb file:
module IRB
def self.add_quotes(str)
str.gsub(/^cli (..+?)(\\+)?$/, 'cli "\1\2\2"') unless str.nil?
end
class StdioInputMethod
alias :old_gets :gets
def gets
IRB::add_quotes(old_gets)
end
end
class ReadlineInputMethod
alias :old_gets :gets
def gets
IRB::add_quotes(old_gets)
end
end
end
This way, any input line matching cli ... will be replaced with cli "..." before it's evaluated.
I don't think it's possible, because the command that you type to irb has to parse as ruby, and all those bare words will report errors like this:
NameError: undefined local variable or method `hello' for main:Object
(My first attempt, I just called it via cli hello.)
But if you didn't mind a more radical change, you could do something like this:
$ cat /tmp/test_cases
hello world
one
two
three
riding the corpse sled
$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)' < /tmp/test_cases
hello world
one
two
three
riding the corpse sled
I just defined a simple function f() here that would show how it works; you could replace f($_) with $Client.cli($_), and set up the $Client global variable in the first -e argument. And you can leave off the < /tmp/test_cases if you want to type them in interactively:
$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)'
hello
hello
world
world
Of course, if you want it to be any more advanced than this, I'd just write a script to do it all, rather than build something hideous from -pe or -ne commands.