7

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

If I invoke:

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 value "false" gets passed. Clearly 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 that I dont have to do

if(ARGV[0]=='true')
1
  • how do you expect your function to interpret non-boolean strings like 'foo'? Commented Feb 10, 2012 at 21:26

5 Answers 5

10

You need to evaluate the command-line argument. Anything passed on the command line is a string, that's all the command line knows about.

For example, you could monkey-patch String (untested):

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your regex would match 'untrue' :)~! So I recommend adding ^ at the front: /^(true|t|yes|y|1)$/i
3

Alternatively, if you want to do more sophisticated commandline parsing with option switches, including Boolean ones, take a look at Ruby's built-in OptionParser.

Comments

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

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

  1. More symmetry -- if you are explicit with tests on the 'true' test, I think you should also be symmetrical on the 'false' test.

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

Comments

2

You CANNOT pass objects from command line. Only object you can pass is a String. I guess at some point in your program you have to do:

if(ARGV[0]=='true')

Comments

0

Here’s a little string helper for converting a string to a bool; it adds a .to_bool method to strings. If the string is equal to true or t or yes or y or 1, the result will be true; otherwise false

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

Examples:

"aaa".to_bool #=> false
"t".to_bool #=> true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.