新手问题 几个条件只能一个为真该如何写

LinuxGit · October 08, 2014 · Last by LinuxGit replied at October 08, 2014 · 1816 hits
-t, --type [gate_type] 
-a, --all
-c, --custom 
-s server 

用 ruby 的 OptionParser 写了一个简单的命令行工具,以上四个参数都是用来指定网关类型的服务器列表,使用时只能使用其中一个。

options[:all] = true
options[:custom] = true
options[:server] 非空
options[:gate_type] 非空

以上四个条件只能一个为真,如何写比较简便呢? 目前的想法是判断为真累加变量数值,超过 1 报错。

嗯累加挺好的

[c1, c2, c3, c4].count {|c| c } <= 1

#1 楼 @luikore 谢谢 你这种写法好赞 太美了。

You need to Sign in before reply, if you don't have an account, please Sign up first.