當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby GetoptLong類用法及代碼示例

本文簡要介紹ruby語言中 GetoptLong類 的用法。

GetoptLong 類允許您解析命令行選項,類似於 GNU getopt_long() C 庫調用。但是請注意, GetoptLong 是純 Ruby 實現。

GetoptLong 允許 POSIX 風格的選項,如 --file 以及單字母選項,如 -f

空選項--(兩個減號)用於結束選項處理。如果選項具有可選參數,這一點尤其重要。

下麵是一個簡單的用法示例:

require 'getoptlong'

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

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
  case opt
    when '--help'
      puts <<-EOF
hello [OPTION] ... DIR

-h, --help:
   show help

--repeat x, -n x:
   repeat x times

--name [name]:
   greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
      EOF
    when '--repeat'
      repetitions = arg.to_i
    when '--name'
      if arg == ''
        name = 'John'
      else
        name = arg
      end
  end
end

if ARGV.length != 1
  puts "Missing dir argument (try --help)"
  exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
  print "Hello"
  if name
    print ", #{name}"
  end
  puts
end

示例命令行:

hello -n 6 --name -- /tmp

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 GetoptLong類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。