I am trying to create a method where I need to pass multiple name parameters with default values but I am getting syntax error, unexpected keyword_next error. How can I rectify it?
Eg method
def action(prev = nil, next = nil)
if prev.present?
# do something
elsif next.present?
# do something
else
# do something else
end
end
How can I make the above code work?
next is a reserved word in Ruby, as it is used to skip one iteration in enumerables. For example in the following code:
my_array = [1, 2, 3, 4]
my_array.each do |number|
next if number == 2
puts number
end
which will oputput:
1
3
4
This means that you can not use it as a variable/parameter name. To fix your code, you just need to rename the variable. For example:
def action(prev = nil, following = nil)
if prev.present?
# do something
elsif following.present?
# do something
else
# do something else
end
end
When debugging shell scripts, I find it helpful to run with xtrace on:
-x xtrace Print commands and parameter
assignments when they are exe-
cuted, preceded by the value
of PS4.
For instance:
$ set -x
$ s='Say again?'
+ s='Say again?'
# Other commands that might mess with the value of $s
$ echo $s
+ echo Say 'again?'
Say again?
I know that Ruby has interactive debuggers such as pry and byebug, but I'm looking for something that will be easy to turn on for logging automated scripts.
I did find an xtrace gem, but it has something to do with a PHP format.
I also see there is a Tracer class and a TracePoint class which do seem to provide a way to print statements as they are executed. But I haven't found any way to print the value of variables (rather than just the variable name):
$ ruby -r tracer trace.rb
#0:/usr/local/Cellar/ruby/2.4.1_1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:Kernel:<: return gem_original_require(path)
#0:trace.rb:1::-: s='Say again?'
#0:trace.rb:2::-: puts s
Say again?
I'd like to have the penultimate line read:
#0:trace.rb:2::-: puts 'Say again?'
Is this possible? Or is there a better way with Ruby?
I was able to build a module that more or less does what I'm looking for:
require 'pry'
=begin
We are always one line behind because the value of assignment comes
_after_ the trace is called. Without this, every assignment would look
like:
x = 1 #=> {:x=>nil}
It would be nice if the trace happened after assignment, but what can
you do?
=end
module Xtrace
# Only run the trace on the main file, not on require'd files.
# Possible room for expansion later.
#files = {$0 => Pry::Code.from_file($0)}
def Xtrace.print_trace
if #prev_line then
if #files[#path] then
line = #files[#path].around(#prev_line, 0).chomp
# When calling a method, don't make it look like it's being defined.
line.gsub!(/^\s*def\s*\b/, '') if #event == :call
values = []
#bind.local_variables.each do |v|
values << {v => #bind.local_variable_get(v)} if line =~ /\b#{v}\b/
end
STDERR.printf "%5s: %s", #prev_line, line
STDERR.printf " #=> %s", values.join(', ') unless values.empty?
STDERR.printf "\n"
end
end
end
#xtrace = TracePoint.trace(:line, :call) do |tp|
tp.disable
#bind=tp.binding
Xtrace.print_trace
# Other than the binding, everything we need to print comes from the
# previous trace call.
#prev_line = tp.lineno
#event=tp.event
#path=tp.path
tp.enable
end
# Need to print the trace one last time after the last line of code.
at_exit do
# It doesn't matter what we do in this last line. Any statement works.
# Also, it's a bit inconvenient that the disable command is itself traced.
#xtrace.disable
end
end
If you put it in a file named xtrace.rb and put in in your library load path, you can begin tracing by adding require 'xtrace'. It prints the line number of each line and method call executed, the actual code and the values of any local variable in the line. For a simple factorial function, the output might look like:
3: def factorial(n)
8: puts factorial(3)
3: factorial(n) #=> {:n=>3}
4: return 1 if n <= 1 #=> {:n=>3}
5: return n*factorial(n-1) #=> {:n=>2}
3: factorial(n) #=> {:n=>2}
4: return 1 if n <= 1 #=> {:n=>2}
5: return n*factorial(n-1) #=> {:n=>1}
3: factorial(n) #=> {:n=>1}
4: return 1 if n <= 1
6
For the moment, it only looks at local variables. It also only traces the executed file and not any loaded files. There's no way to enable or disable traces just yet. The trace begins when you require the module and ends when the execution does. Trace output goes to STDERR and the format is hardcoded.
If you use this module, watch out that you don't leak sensitive information such as passwords, API keys or PII.
Here's some code:
$ cat 1.rb
#!/usr/bin/env ruby
def f p1 = nil
unless p1 # TODO
puts 'no parameters passed'
end
end
f
f nil
$ ./1.rb
no parameters passed
no parameters passed
The question is, is there a way to distinguish between no arguments and one nil argument passed?
UPD
I decided to add a use case in javascript to make things hopefully clearer:
someProp: function(value) {
if (arguments.length) {
this._someProp = value;
}
return this._someProp;
}
There are three ways in general use. One way is to use the default value to set another variable indicating whether or not the default value was evaluated:
def f(p1 = (no_argument_passed = true; nil))
'no arguments passed' if no_argument_passed
end
f # => 'no arguments passed'
f(nil) # => nil
The second way is to use some object that is only known inside the method as default value, so that it is impossible for an outsider to pass that object in:
-> {
undefined = BasicObject.new
define_method(:f) do |p1 = undefined|
'no arguments passed' if undefined.equal?(p1)
end
}.()
f # => 'no arguments passed'
f(nil) # => nil
Of these two, the first one is more idiomatic. The second one (actually, a variation of it) is used inside Rubinius, but I have never encountered it anywhere else.
A third solution would be to take a variable number of arguments using a splat:
def f(*ps)
num_args = ps.size
raise ArgumentError, "wrong number of arguments (#{num_args} for 0..1)" if num_args > 1
'no arguments passed' if num_args.zero?
end
f # => 'no arguments passed'
f(nil) # => nil
Note that this requires you to re-implement Ruby's arity checking by hand. (And we still haven't gotten it right, because this raises the exception inside the method, whereas Ruby would raise it at the call site.) It also requires you to manually document your method signature because automated documentation generators such as RDoc or YARD will infer an arbitrary number of parameters instead of a single optional one.
You could request for splat arguments:
def f(*args)
if args.empty?
puts 'no parameters passed'
else
p1 = args[0]
...
end
end
Some other option might be to have a private object to indicate no parameter passed:
def initialize
#no_param_passed = Object.new
end
def f(p1 = #no_param_passed)
if p1 == #no_param_passed
puts 'no parameters passed'
end
end
Can anyone help me to figure out the the use of yield and return in Ruby. I'm a Ruby beginner, so simple examples are highly appreciated.
Thank you in advance!
The return statement works the same way that it works on other similar programming languages, it just returns from the method it is used on.
You can skip the call to return, since all methods in ruby always return the last statement. So you might find method like this:
def method
"hey there"
end
That's actually the same as doing something like:
def method
return "hey there"
end
The yield on the other hand, excecutes the block given as a parameter to the method. So you can have a method like this:
def method
puts "do somthing..."
yield
end
And then use it like this:
method do
puts "doing something"
end
The result of that, would be printing on screen the following 2 lines:
"do somthing..."
"doing something"
Hope that clears it up a bit. For more info on blocks, you can check out this link.
yield is used to call the block associated with the method. You do this by placing the block (basically just code in curly braces) after the method and its parameters, like so:
[1, 2, 3].each {|elem| puts elem}
return exits from the current method, and uses its "argument" as the return value, like so:
def hello
return :hello if some_test
puts "If it some_test returns false, then this message will be printed."
end
But note that you don't have to use the return keyword in any methods; Ruby will return the last statement evaluated if it encounters no returns. Thus these two are equivelent:
def explicit_return
# ...
return true
end
def implicit_return
# ...
true
end
Here's an example for yield:
# A simple iterator that operates on an array
def each_in(ary)
i = 0
until i >= ary.size
# Calls the block associated with this method and sends the arguments as block parameters.
# Automatically raises LocalJumpError if there is no block, so to make it safe, you can use block_given?
yield(ary[i])
i += 1
end
end
# Reverses an array
result = [] # This block is "tied" to the method
# | | |
# v v v
each_in([:duck, :duck, :duck, :GOOSE]) {|elem| result.insert(0, elem)}
result # => [:GOOSE, :duck, :duck, :duck]
And an example for return, which I will use to implement a method to see if a number is happy:
class Numeric
# Not the real meat of the program
def sum_of_squares
(to_s.split("").collect {|s| s.to_i ** 2}).inject(0) {|sum, i| sum + i}
end
def happy?(cache=[])
# If the number reaches 1, then it is happy.
return true if self == 1
# Can't be happy because we're starting to loop
return false if cache.include?(self)
# Ask the next number if it's happy, with self added to the list of seen numbers
# You don't actually need the return (it works without it); I just add it for symmetry
return sum_of_squares.happy?(cache << self)
end
end
24.happy? # => false
19.happy? # => true
2.happy? # => false
1.happy? # => true
# ... and so on ...
Hope this helps! :)
def cool
return yield
end
p cool {"yes!"}
The yield keyword instructs Ruby to execute the code in the block. In this example, the block returns the string "yes!". An explicit return statement was used in the cool() method, but this could have been implicit as well.
Is there any way to kick off OptionParser several times in one Ruby program, each with different sets of options?
For example:
$ myscript.rb --subsys1opt a --subsys2opt b
Here, myscript.rb would use subsys1 and subsys2, delegating their options handling logic to them, possibly in a sequence where 'a' is processed first, followed by 'b' in separate OptionParser object; each time picking options only relevant for that context.
A final phase could check that there is nothing unknown left after each part processed theirs.
The use cases are:
In a loosely coupled front-end program, where various components have different arguments, I don't want 'main' to know about everything, just to delegate sets of arguments/options to each part.
Embedding some larger system like RSpec into my application, and I'd to simply pass a command-line through their options without my wrapper knowing those.
I'd be OK with some delimiter option as well, like -- or --vmargs in some Java apps.
There are lots of real world examples for similar things in the Unix world (startx/X, git plumbing and porcelain), where one layer handles some options but propagates the rest to the lower layer.
Out of the box, this doesn't seem to work. Each OptionParse.parse! call will do exhaustive processing, failing on anything it doesn't know about.
I guess I'd happy to skip unknown options.
Any hints, perhaps alternative approaches are welcome.
I needed a solution that wouldn't throw OptionParser::InvalidOption ever, and couldn't find an elegant solution among the current answers. This monkey patch is based on one of the other answers but cleans it up and makes it work more like the current order! semantics. But see below for an unsolved issue inherent to multiple-pass option parsing.
class OptionParser
# Like order!, but leave any unrecognized --switches alone
def order_recognized!(args)
extra_opts = []
begin
order!(args) { |a| extra_opts << a }
rescue OptionParser::InvalidOption => e
extra_opts << e.args[0]
retry
end
args[0, 0] = extra_opts
end
end
Works just like order! except instead of throwing InvalidOption, it leaves the unrecognized switch in ARGV.
RSpec tests:
describe OptionParser do
before(:each) do
#parser = OptionParser.new do |opts|
opts.on('--foo=BAR', OptionParser::DecimalInteger) { |f| #found << f }
end
#found = []
end
describe 'order_recognized!' do
it 'finds good switches using equals (--foo=3)' do
argv = %w(one two --foo=3 three)
#parser.order_recognized!(argv)
expect(#found).to eq([3])
expect(argv).to eq(%w(one two three))
end
it 'leaves unknown switches alone' do
argv = %w(one --bar=2 two three)
#parser.order_recognized!(argv)
expect(#found).to eq([])
expect(argv).to eq(%w(one --bar=2 two three))
end
it 'leaves unknown single-dash switches alone' do
argv = %w(one -bar=2 two three)
#parser.order_recognized!(argv)
expect(#found).to eq([])
expect(argv).to eq(%w(one -bar=2 two three))
end
it 'finds good switches using space (--foo 3)' do
argv = %w(one --bar=2 two --foo 3 three)
#parser.order_recognized!(argv)
expect(#found).to eq([3])
expect(argv).to eq(%w(one --bar=2 two three))
end
it 'finds repeated args' do
argv = %w(one --foo=1 two --foo=3 three)
#parser.order_recognized!(argv)
expect(#found).to eq([1, 3])
expect(argv).to eq(%w(one two three))
end
it 'maintains repeated non-switches' do
argv = %w(one --foo=1 one --foo=3 three)
#parser.order_recognized!(argv)
expect(#found).to eq([1, 3])
expect(argv).to eq(%w(one one three))
end
it 'maintains repeated unrecognized switches' do
argv = %w(one --bar=1 one --bar=3 three)
#parser.order_recognized!(argv)
expect(#found).to eq([])
expect(argv).to eq(%w(one --bar=1 one --bar=3 three))
end
it 'still raises InvalidArgument' do
argv = %w(one --foo=bar)
expect { #parser.order_recognized!(argv) }.to raise_error(OptionParser::InvalidArgument)
end
it 'still raises MissingArgument' do
argv = %w(one --foo)
expect { #parser.order_recognized!(argv) }.to raise_error(OptionParser::MissingArgument)
end
end
end
Problem: normally OptionParser allows abbreviated options, provided there are enough characters to uniquely identify the intended option. Parsing options in multiple stages breaks this, because OptionParser doesn't see all the possible arguments in the first pass. For example:
describe OptionParser do
context 'one parser with similar prefixed options' do
before(:each) do
#parser1 = OptionParser.new do |opts|
opts.on('--foobar=BAR', OptionParser::DecimalInteger) { |f| #found_foobar << f }
opts.on('--foo=BAR', OptionParser::DecimalInteger) { |f| #found_foo << f }
end
#found_foobar = []
#found_foo = []
end
it 'distinguishes similar prefixed switches' do
argv = %w(--foo=3 --foobar=4)
#parser1.order_recognized!(argv)
expect(#found_foobar).to eq([4])
expect(#found_foo).to eq([3])
end
end
context 'two parsers in separate passes' do
before(:each) do
#parser1 = OptionParser.new do |opts|
opts.on('--foobar=BAR', OptionParser::DecimalInteger) { |f| #found_foobar << f }
end
#parser2 = OptionParser.new do |opts|
opts.on('--foo=BAR', OptionParser::DecimalInteger) { |f| #found_foo << f }
end
#found_foobar = []
#found_foo = []
end
it 'confuses similar prefixed switches' do
# This is not generally desirable behavior
argv = %w(--foo=3 --foobar=4)
#parser1.order_recognized!(argv)
#parser2.order_recognized!(argv)
expect(#found_foobar).to eq([3, 4])
expect(#found_foo).to eq([])
end
end
end
Assuming the order in which the parsers will run is well defined, you can just store the extra options in a temporary global variable and run OptionParser#parse! on each set of options.
The easiest way to do this is to use a delimiter like you alluded to. Suppose the second set of arguments is separated from the first by the delimiter --. Then this will do what you want:
opts = OptionParser.new do |opts|
# set up one OptionParser here
end
both_args = $*.join(" ").split(" -- ")
$extra_args = both_args[1].split(/\s+/)
opts.parse!(both_args[0].split(/\s+/))
Then, in the second code/context, you could do:
other_opts = OptionParser.new do |opts|
# set up the other OptionParser here
end
other_opts.parse!($extra_args)
Alternatively, and this is probably the "more proper" way to do this, you could simply use OptionParser#parse, without the exclamation point, which won't remove the command-line switches from the $* array, and make sure that there aren't options defined the same in both sets. I would advise against modifying the $* array by hand, since it makes your code harder to understand if you are only looking at the second part, but you could do that. You would have to ignore invalid options in this case:
begin
opts.parse
rescue OptionParser::InvalidOption
puts "Warning: Invalid option"
end
The second method doesn't actually work, as was pointed out in a comment. However, if you have to modify the $* array anyway, you can do this instead:
tmp = Array.new
while($*.size > 0)
begin
opts.parse!
rescue OptionParser::InvalidOption => e
tmp.push(e.to_s.sub(/invalid option:\s+/,''))
end
end
tmp.each { |a| $*.push(a) }
It's more than a little bit hack-y, but it should do what you want.
I've got the same problem, and I found the following solution:
options = ARGV.dup
remaining = []
while !options.empty?
begin
head = options.shift
remaining.concat(parser.parse([head]))
rescue OptionParser::InvalidOption
remaining << head
retry
end
end
For posterity, you can do this with the order! method:
option_parser.order!(args) do |unrecognized_option|
args.unshift(unrecognized_option)
end
At this point, args has been modified - all known options were consumed and handled by option_parser - and can be passed to a different option parser:
some_other_option_parser.order!(args) do |unrecognized_option|
args.unshift(unrecognized_option)
end
Obviously, this solution is order-dependent, but what you are trying to do is somewhat complex and unusual.
One thing that might be a good compromise is to just use -- on the command line to stop processing. Doing that would leave args with whatever followed --, be that more options or just regular arguments.
I also needed the same... it took me a while but a relatively simple way has worked fine in the end.
options = {
:input_file => 'input.txt', # default input file
}
opts = OptionParser.new do |opt|
opt.on('-i', '--input FILE', String,
'Input file name',
'Default is %s' % options[:input_file] ) do |input_file|
options[:input_file] = input_file
end
opt.on_tail('-h', '--help', 'Show this message') do
puts opt
exit
end
end
extra_opts = Array.new
orig_args = ARGV.dup
begin
opts.parse!(ARGV)
rescue OptionParser::InvalidOption => e
extra_opts << e.args
retry
end
args = orig_args & ( ARGV | extra_opts.flatten )
"args" will contain all command line arguments without the ones already parsed into the "options" hash. I'm passing this "args" to an external program to be called from this ruby script.
Another solution which relies on parse! having a side effect on the argument list even if an error is thrown.
Let's define a method which tries to scan some argument list using a user defined parser and calls itself recursively when an InvalidOption error is thrown, saving the invalid option for later with eventual parameters:
def parse_known_to(parser, initial_args=ARGV.dup)
other_args = [] # this contains the unknown options
rec_parse = Proc.new { |arg_list| # in_method defined proc
begin
parser.parse! arg_list # try to parse the arg list
rescue OptionParser::InvalidOption => e
other_args += e.args # save the unknown arg
while arg_list[0] && arg_list[0][0] != "-" # certainly not perfect but
other_args << arg_list.shift # quick hack to save any parameters
end
rec_parse.call arg_list # call itself recursively
end
}
rec_parse.call initial_args # start the rec call
other_args # return the invalid arguments
end
my_parser = OptionParser.new do
...
end
other_options = parse_known_to my_parser
I ran into a similar problem when I was writing a script that wrapped a ruby gem, which needed its own options with arguments passed to it.
I came up with the following solution in which it supports options with arguments for the wrapped tool. It works by parsing it through the first optparser, and separates what it can't use into a seperate array (which can be re-parsed again with another optparse).
optparse = OptionParser.new do |opts|
# OptionParser settings here
end
arguments = ARGV.dup
secondary_arguments = []
first_run = true
errors = false
while errors || first_run
errors = false
first_run = false
begin
optparse.order!(arguments) do |unrecognized_option|
secondary_arguments.push(unrecognized_option)
end
rescue OptionParser::InvalidOption => e
errors = true
e.args.each { |arg| secondary_arguments.push(arg) }
arguments.delete(e.args)
end
end
primary_arguments = ARGV.dup
secondary_arguments.each do |cuke_arg|
primary_arguments.delete(cuke_arg)
end
puts "Primary Args: #{primary_arguments}"
puts "Secondary Args: #{secondary_args}"
optparse.parse(primary_arguments)
# Can parse the second list here, if needed
# optparse_2.parse(secondary_args)
Probably not the greatest or most efficient way of doing it, but it worked for me.
I've just moved from Python. Python's ArgumentParser has great method parse_known_args(). But it still doesn't accept second argument, such as:
$ your-app -x 0 -x 1
First -x 0 is your app's argument. Second -x 1 can belong to the target app that you need to forward to. ArgumentParser will raise error in this case.
Now come back to Ruby, you can use #order. Fortunately it accepts unlimited duplicate arguments. For example you need -a and -b. Your target app needs another -a and a mandatory argument some (note that there is no prefix -/--). Normally #parse will ignore mandatory arguments. But with #order, you will get the rest -- great. Note that you have to pass your own app's arguments first, then the target app's arguments.
$ your-app -a 0 -b 1 -a 2 some
And the code should be:
require 'optparse'
require 'ostruct'
# Build default arguments
options = OpenStruct.new
options.a = -1
options.b = -1
# Now parse arguments
target_app_argv = OptionParser.new do |opts|
# Handle your own arguments here
# ...
end.order
puts ' > Options = %s' % [options]
puts ' > Target app argv = %s' % [target_app_argv]
Tada :-)
My attempt:
def first_parse
left = []
begin
#options.order!(ARGV) do |opt|
left << opt
end
rescue OptionParser::InvalidOption => e
e.recover(args)
left << args.shift
retry
end
left
end
In my case, I want to scan the options and pick up any predefined options that may set debugging levels, output files, etc. Then I am going to load custom processors which may add to the options. After all the custom processors have been loaded, I call #options.parse!(left) to process the left over options. Note that --help is built in to the options so if you want to not recognize help the first time, you need to do ' OptionParser::Officious.delete('help')' before you create the OptParser and then add in your own help option
Parse options up until the first unknown option ... the block might be called multiple times, so make sure that is safe ...
options = {
:input_file => 'input.txt', # default input file
}
opts = OptionParser.new do |opt|
opt.on('-i', '--input FILE', String,
'Input file name',
'Default is %s' % options[:input_file] ) do |input_file|
options[:input_file] = input_file
end
opt.on_tail('-h', '--help', 'Show this message') do
puts opt
exit
end
end
original = ARGV.dup
leftover = []
loop do
begin
opts.parse(original)
rescue OptionParser::InvalidOption
leftover.unshift(original.pop)
else
break
end
end
puts "GOT #{leftover} -- #{original}"