Jared Beck
Jared Beck

Reputation: 17528

Coerce to boolean

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:

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

Upvotes: 4

Views: 4702

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 96984

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

Upvotes: 5

Related Questions