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.
!!nil# => false
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 on NilClass? 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:
classStringdefto_bool# self is the implied receiver of the downcase methodreturntrueifdowncase=="true"returnfalseifdowncase=="false"# implicitly return nil, no code needed hereendend
...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 defined nil.to_bool as false.
That could get weird because of the way nil and false are both treated as false in boolean expressions in Ruby. For that reason, if I wanted to do something similar I would probably make two methods, true? and false? to make sure something that is supposed to say "false" REALLY says "false".
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