There are times when you will run into
nil == false
=> false
'true' == true
=> false
'false' == false
=> false
Here is my solution to this problem. (not sure if this is the best way, but I love it)
NOTE: If you are using rails, create a file called extend_string.rb
in config/initializers
folder. Then add the code below.
Or just import it somewhere before you start your ruby app.
class NilClass
def self.to_bool
false
end
def to_bool
false
end
end
class String
def to_bool
return true if self.downcase == "true"
return false if self.downcase == "false"
return nil
end
end
Now that you have this in your code, you can run
nil.to_bool == false
=> true
'true'.to_bool == true
=> true
'false'.to_bool == false
=> true
'TRUE'.to_bool == true
=> true
'FaLSE'.to_bool == false
=> true
If you there is any other way to do this, please let me know so I can improve my code.
Thankz :D
Top comments (2)
I like the brevity of your approach. Half the fun of Ruby is the flexibility it has to do this kind of stuff. This article makes a nice intro to monkey patching.
Another common way to convert a value to boolean is to double negate it.
That doesn't help your string examples, since strings are always true in Ruby regardless of content, but it could be of interest for nil and other objects.
I'm curious, why did you define
to_bool
as a class method onNilClass
? Your examples show use of the instance method, but not the class method.Since you specifically invited improvements, I'll mention that your
String#to_bool
method can be made a little briefer:...and that it's a little odd to return nil (which is not a boolean value) in a method called
to_bool
, especially if you've definednil.to_bool
as false.That could get weird because of the way
nil
andfalse
are both treated asfalse
in boolean expressions in Ruby. For that reason, if I wanted to do something similar I would probably make two methods,true?
andfalse?
to make sure something that is supposed to say "false" REALLY says "false".thank you for your comment.
I use to_bool because sometime client side send me
So I treid to make it simpler by
params[:is_active].to_bool
I am thinking about how to use your approach in the future project.
But please let me know if I can improve my code for this case?
Thank you again