Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coerce to boolean

Tags:

ruby

Given an expression which may return either a truthy value or nil,

truthy_or_nil = [true, 'truthy', nil].sample

how can I coerce the result into a boolean without my colleagues or linter complaining?

!!truthy_or_nil # Hard to see the !! on a long line, unclear
truthy_or_nil || false # Linter complains "you can simplify this"
!truthy_or_nil.nil? # Unclear on a long line
truthy_or_nil ? true : false # Hard to see on long line, too much typing

I have looked at the following questions and found them to be unrelated:

  • Why use !! to coerce a variable to boolean for use in a conditional expression? - This question is more specific than my question because it is about use of !! in conditional expressions. Also, it's about JS.
  • In environments that take Boolean arguments, is it a good idea to wrap all functions instead of allowing them to be implicitly coerced? - This question is more about the merit of the technique than the technique itself.

If this question is determined to be too broad, I will understand. If so, is there a better place to ask it?

like image 885
Jared Beck Avatar asked Oct 23 '25 17:10

Jared Beck


1 Answers

The obvious solution is to create a method in Kernel à la Array, Integer, String etc.:

module Kernel
  def Boolean val
    !!val
  end
end

You could also add to_bool to Object, à la to_s:

class Object
  def to_bool
    !!self
  end
end

Or do both and have one call the other. Barring either of these, I’d say !!x is the most common idiom, but is lesser known to those without a C background from what I’ve seen.

Really, this should probably be to_b to keep in-line with to_a vs. to_ary, etc. (read more). But to_b seems ambiguous to me (to bytes? to binary?).

like image 162
Andrew Marshall Avatar answered Oct 26 '25 07:10

Andrew Marshall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!