我想知道如何将假值传递给我的ruby脚本。
如果我调用:
ruby myscript.rb false
然后在我的脚本中,如果我说:
my_class.new(*ARGV)
or my_class.new(ARGV[0])
基本上传递值为“false”的字符串。显然,如果我说
if(ARGV[0]){ do something} .. this gets executed even if value passed is false.
我可以将我的功能签名更改为自动隐藏参数到布尔..所以我不必这样做
if(ARGV[0]=='true')
答案 0 :(得分:9)
您需要评估命令行参数。在命令行上传递的任何内容都是一个字符串,这是命令行所知道的。
例如,您可以使用Monkey-patch String(未经测试):
class String
def to_b
self =~ /^(true|t|yes|y|1)$/i
end
end
或编写实用程序,或使用命令行选项解析器(长期最好的选择),或者......
答案 1 :(得分:3)
def to_b(string)
case string
when /^(true|t|yes|y|1)$/i then true
when /^(false|f|no|n|0)$/i then false
else raise "Cannot convert to boolean: #{string}"
end
end
这基于Dave Newton's answer,有两点不同:
更加对称 - 如果你明确对'真''测试进行测试,我认为你也应该在'假'测试中对称。
对/(monkey|duck) p(at|un)ching)/
等String
等关键类说“不”!
答案 2 :(得分:2)
或者,如果您想使用选项开关(包括布尔值开关)进行更复杂的命令行解析,请查看Ruby的内置OptionParser。
答案 3 :(得分:1)
您无法从命令行传递对象。只有你可以传递的对象是一个String。我想在你的程序中你需要做的一些事情:
if(ARGV[0]=='true')