2013-03-20 1 views
0

optparse를 사용하여 명령 행 옵션을 사용하는 방법을 배우려하고 있습니다. 그러나 클래스 문서 및 예제에서 찾을 수있는 것처럼 작동하려면 어려움을 겪고 있습니다. 온라인. 특히 -h 옵션을 전달하면 아무 것도 나오지 않습니다. ARGV를 출력하고 -h를 수신한다는 것을 보여줄 수 있지만 opts.banner 및 opts를 표시하지 않습니다. 내가 여기서 무엇을 놓치고 있니? 당신은 당신과 같이, new에게 줄 블록 외부에서이 작업을 수행해야합니다ruby ​​optparse가 opts를 출력 할 수 없습니다.

op = OptionParser.new do 
    # what you have now 
end 

op.parse! 

참고 :

class TestThing 

def self.parse(args) 
    options = {} 
     options[:time]  = 0 
     options[:operation] = :add 
     options[:input_file] = ARGV[-2] 
     options[:output_file] = ARGV[-1] 
      optparse = OptionParser.new do |opts| 
       opts.banner = "Usage:[OPTIONS] input_file output_file" 

       opts.separator = "" 
       opts.separator = "Specific Options:" 


       opts.on('-o', '--operation [OPERATION]', "Add or Subtract time, use 'add' or 'sub'") do |operation| 
        optopns[:operation] = operation.to_sym 
       end 

       opts.on('-t', '--time [TIME]', "Time to be shifted, in milliseconds") do |time| 
        options[:time] = time 
       end 

       opts.on_tail("-h", "--help", "Display help screen") do 
        puts opts 
        exit 
       end 

       opt_parser.parse!(args) 
       options 
      end 
end 
end 

답변

0

당신은 그것을 parse!를 호출 한 후 OptionParser.new의 결과 붙잡고해야합니다

class TestThing 

def self.parse(args) 
    options = {} 
     options[:time]  = 0 
     options[:operation] = :add 
     options[:input_file] = ARGV[-2] 
     options[:output_file] = ARGV[-1] 
      optparse = OptionParser.new do |opts| 
       opts.banner = "Usage:[OPTIONS] input_file output_file" 
       # all the rest of your app 
      end 
      optparse.parse!(args) 
end 
end 

은 (내가 무엇을 의미하는지는 명확하게하기에 들여 쓰기를 떠났지만 보조 노트에, 당신은 당신이 단점을 들여 경우 작업 할 코드를 쉽게 찾을 수 있습니다 istently).

또한 -h--help을 추가 할 필요가 없습니다. OptionParser은 자동으로 제공하며 정확하게 구현 한 것입니다.

+0

Ive는 이미 8 행과 5 행을 맨 아래부터 가져 왔으며, 이것을 잘못 구현 했습니까? –

+0

당신은 새로운 블럭 밖에서 그것을 부를 필요가 있습니다 - 내 대답을 업데이트해서 내 뜻을 나타냅니다 (잘하면) – davetron5000

관련 문제