Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value with space to Ruby script

Tags:

ruby

I've started to get the option parser within Ruby to work with a general amount of success. Unfortunately ruby-docs isn't particularly helpful in what I'm looking to do. is it possible to pass multiple values to one argument, or define an argument as an array and pass multiple values to it?

require 'optparse'

@user_name = nil

opts = OptionParser.new
opts.on("-n name", "--name name", "Name Input"){|n|
@user_name = n
}
opts.parse!(ARGV)

if @user_name.nil? == false
  puts @user_name
else
  puts "Nil Value"
end

Right now if you run this:

ruby nametest.rb -n John Doe

You will get:

John

I'm looking to have both the first and last name printed on the screen.

like image 543
SecurityGate Avatar asked Jan 28 '26 09:01

SecurityGate


1 Answers

This isn't a ruby problem, but rather how most command line parsers work. A space delimits a token, so you need to group with quotes or escape space characters.

ruby nametest.rb -n "John Doe"
# or
ruby nametest.rb -n John\ Doe
like image 172
numbers1311407 Avatar answered Jan 30 '26 01:01

numbers1311407



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!