DEV Community

Discussion on: Ruby: Getting boolean from string or nil

Collapse
 
briankephart profile image
Brian Kephart

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
Enter fullscreen mode Exit fullscreen mode

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:

class String
  def to_bool
    # self is the implied receiver of the downcase method
    return true if downcase == "true"
    return false if downcase == "false"
    # implicitly return nil, no code needed here
  end
end
Enter fullscreen mode Exit fullscreen mode

...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.

'string'.to_bool
# => nil
'string'.to_bool.to_bool
# => false
Enter fullscreen mode Exit fullscreen mode

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".

class String
  def true?
    downcase == 'true'
  end

  def false?
    downcase == 'false'
  end
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sakko profile image
SaKKo • Edited

thank you for your comment.

I use to_bool because sometime client side send me

is_active: nil
is_active: "false"
is_active: "True"

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