tags:

views:

37

answers:

2
opts = GetoptLong.new(
  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

I have this kind of declaration for optlong. Can anyone tell me if opts works as an array or as a hash and also what are the values in opts. One more thing

opts.each do |opt,args|

what are the valuse in opt and args respeectively?

Please help me out

A: 

opt,arg:

opt is the actual option passed, which in your case would be help/repeat/name. arg would be the value of the argument.

For instance, if you give

--name amit then you would get arg value = amit

Also, it is most likely that options is a hash.

NO_ARGUMENT: It takes just '-h'/'--help', but does not take any argument.

REQUIRED_ARGUMENT: It needs an argument to be specified. For example just ' --repeat' will be rejected.

OPTIONAL_ARGUMENT: You can either supply an argument to the option, or not. e.g., think of ls. You can say 'ls' and it will list the contents of directory, or you could say 'ls .'/'ls '...

EDIT: Please look at this for a brief explanation of Getopt (both variations). http://ruby.about.com/od/advancedruby/a/commandoptions.htm

rmk
thanks rmk but one more thing like when comaand line argument lke -n(suppose for name)-n sachin then how it goes like sachin is the value of args and then whts the opt value ???
amit singh tomar
i think it like that opts["name"]=-n and the opt=repeat and arg=-n and whwn u passed cmd line argument like -n amit then whole thing is like opts["name"]=amit is it not that i want to know??
amit singh tomar
Yes, you are right. In ruby, a hash value can be obtained by strings / symbols, like opts[:name] or opts["name"]. It is nicer to use symbols though.
rmk
A: 

opt holds the 'long' version of the option. arg holds the corresponding argument. I usually write something similar to the code below when I use getoptlong.

opts.each do |opt, arg|
  case opt
  when '--help'
    RDoc::usage
    exit(0)
  when '--repeat'
    puts "--repeat argument was #{arg}"
  end
end

So if you enter foo.rb -n 8, arg will hold 8 when the '--repeat' branch is executed. Hope this helps

reprazent74
thanks but one more here opts supposed to be what its an array or hash or simple object of class getoptlong nd in our command line why we r not giving the 'long' version of option
amit singh tomar
I am not sure what you mean I'm afraid. Could you be more specific?
reprazent74
i want to know how to find contents of opts is there any method to find out??
amit singh tomar