gpt4 book ai didi

ruby - 如何使用 OptionParser 处理目录或文件

转载 作者:数据小太阳 更新时间:2023-10-29 08:34:42 25 4
gpt4 key购买 nike

我发现自己经常这样做:

optparse = OptionParser.new do |opts|
options[:directory] = "/tmp/"
opts.on('-d','--dir DIR', String, 'Directory to put the output in.') do |x|
raise "No such directory" unless File.directory?(x)
options[:directory] = x
end
end

如果我可以指定 DirPathname 而不是 String 会更好。是否有一种模式或我的 Ruby 式方法可以做到这一点?

最佳答案

您可以配置 OptionParser 以接受(例如)路径名

require 'optparse'
require 'pathname'

OptionParser.accept(Pathname) do |pn|
begin
Pathname.new(pn) if pn
# code to verify existence
rescue ArgumentError
raise OptionParser::InvalidArgument, s
end
end

然后您可以将代码更改为

opts.on('-d','--dir DIR',Pathname, 'Directory to put the output in.') do |x|

关于ruby - 如何使用 OptionParser 处理目录或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3712529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com