ruby - Coerce to boolean -
given expression may return either truthy value or nil,
truthy_or_nil = [true, 'truthy', nil].sample
how can coerce result boolean without colleagues or linter complaining?
!!truthy_or_nil # hard see !! on long line, unclear truthy_or_nil || false # linter complains "you can simplify this" !truthy_or_nil.nil? # unclear on long line truthy_or_nil ? true : false # hard see on long line, typing
i have looked @ following questions , found them unrelated:
- why use !! coerce variable boolean use in conditional expression? - question more specific question because use of
!!
in conditional expressions. also, it's js. - in environments take boolean arguments, idea wrap functions instead of allowing them implicitly coerced? - question more merit of technique technique itself.
if question determined too broad, understand. if so, there better place ask it?
the obvious solution create method in kernel à la array
, integer
, string
etc.:
module kernel def boolean val !!val end end
you add to_bool
† object, à la to_s
:
class object def to_bool !!self end end
or both , have 1 call other. barring either of these, i’d !!x
common idiom, lesser known without c background i’ve seen.
†really, should to_b
keep in-line to_a
vs. to_ary
, etc. (read more). to_b
seems ambiguous me (to bytes? binary?).
Comments
Post a Comment