Passing commandline parameter (arguments) to ruby file using optparser

Ruby file accepts from command prompt in the form of array.

Passing parameters

ruby input.rb TOI DH TimesNew

Accessing parameters

 # input.rb
p ARGV
# => ["TOI", "DH", "TimesNew"]
p ARGV[0]
# => "TOI"
p ARGV[1]
# => "DH"

Optparser : parses commandline options in more effective way using OptParser class.and we can access options as hashed parameters.

Passing parameters

ruby input.rb -P"The Times of India" --category"article"

Accessing parameters

 
# input.rb
require 'optparser'

options = ARGV.getopts("P:", 'category')

p options
# => { 'P' => 'The Times of India', :category => 'article' }

p options['P']
# => "The Times of India"
Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s