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:

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

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -