Passing a boolean parameter in ruby

I am wondering how to pass a false value to my ruby ​​script.

If I call:

ruby myscript.rb false 

and then in my script if I say:

 my_class.new(*ARGV) or my_class.new(ARGV[0]) 

basically a string with the value "false" is passed. Clear if i say

 if(ARGV[0]){ do something} .. this gets executed even if value passed is false. 

Can I change my function signature to auto-covert paramter to boolean .. so I don't have to do

 if(ARGV[0]=='true') 
+4
source share
4 answers

You need to evaluate the command line argument. All that was passed on the command line is a line that the whole team knows about.

For example, you can defuse String (untested):

 class String def to_b self =~ /^(true|t|yes|y|1)$/i end end 

Either write a utility or use the command line parser (long-term best option) or ...

+8
source
 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 

This is based on Dave Newton's answer with two differences:

  • More symmetry - if you explicitly use tests in the "true" test, I think you should also be symmetrical in the "false" test.

  • Just say no to /(monkey|duck) p(at|un)ching)/ key classes like String !

+3
source

Alternatively, if you want to do more complex command line parsing with option switches, including logical ones, take a look at the built-in Ruby OptionParser .

+2
source

You cannot pass objects from the command line. Only the object you can pass is a string. I think at some point in your program you need to do:

 if(ARGV[0]=='true') 
+1
source

Source: https://habr.com/ru/post/1395844/


All Articles