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

LinuxGit · 2014年10月08日 · 最后由 LinuxGit 回复于 2014年10月08日 · 1814 次阅读
-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 谢谢 你这种写法好赞 太美了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号