是否有任何标准方法可以避免 Ruby 中的真实性,或者我需要推出自己的解决方案,例如
class FalseClass
def to_bool
self
end
end
class TrueClass
def to_bool
self
end
end
true.to_bool # => true
false.to_bool # => false
nil.to_bool # => NoMethodError
42.to_bool # => NoMethodError
背景:我知道这to_bool
会违背 Ruby 的宽容性质,但我正在玩三元逻辑,并希望避免意外地做类似的事情
require "ternary_logic"
x = UNKNOWN
do_something if x
我正在使用三元逻辑,因为我正在编写一个室友共享网站的解析器(供个人使用,而非商业用途),并且某些字段可能缺少信息,因此不知道该位置是否是否符合我的标准。但是,我会尝试限制使用三元逻辑的代码数量。