强制布尔值

时间:2014-12-06 01:06:02

标签: ruby

给定一个可能返回真值或nil的表达式,

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

如何在没有我的同事或linter抱怨的情况下将结果强制转换为布尔值?

!!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

我查看了以下问题并发现它们不相关:

如果确定此问题为too broad,我会理解。如果是这样,有没有更好的地方问它?

1 个答案:

答案 0 :(得分:5)

显而易见的解决方案是在内核àArrayIntegerString等中创建方法:

module Kernel
  def Boolean val
    !!val
  end
end

您还可以将to_bool 添加到对象,àlato_s

class Object
  def to_bool
    !!self
  end
end

或两者兼而有之。除了其中任何一个,我会说!!x是最常见的习语,但对于那些没有我背景的C背景的人来说,鲜为人知。

实际上,to_bto_ato_ary保持一致to_b。{{3 }})。但是{{1}}对我来说似乎不明确(对于字节?到二进制?)。